Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the highlighted color of a UIButton? [duplicate]

I created a navigation button in my UINavigationController. I set it to be highlighted when touched:

[someButton setShowsTouchWhenHighlighted:YES];

Is there a way to change the highlighted color to something other than the default white?

like image 520
Code Monkey Avatar asked Nov 30 '13 13:11

Code Monkey


3 Answers

Try to Override the UIButton with the following Method.. and just change the backgroud color of button when its in highlighted state.

- (void)setHighlighted:(BOOL)highlighted {
    [super setHighlighted:highlighted];

    if (highlighted) {
        self.backgroundColor = [UIColor Your Customcolor];
    }
    else{
        self.backgroundColor = [UIColor Your DefaultColor];
    }   

}

Try it..hope it helps

like image 193
User 1531343 Avatar answered Nov 18 '22 03:11

User 1531343


You can use setBackgroundImage:forState: to set the background image for the button when highlighted.

ex:

As suggested by Tim in their answer here, you can create aUIImage from UIColor:

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

Then set image as button's background image when highlighted

[button setBackgroundImage:[self imageWithColor:[UIColor blueColor]] forState:UIControlStateHighlighted];

like image 47
bradley Avatar answered Nov 18 '22 01:11

bradley


In Swift:

import UIKit

class CustomUIButtonForUIToolbar: UIButton {

    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
        super.drawRect(rect)

        self.layer.borderColor = UIColor.blueColor().CGColor
        self.layer.borderWidth = 1.0
        self.layer.cornerRadius = 5.0
        self.clipsToBounds = true
        self.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)

        self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
    }

    override var highlighted: Bool {
        didSet {

            if (highlighted) {
                self.backgroundColor = UIColor.blueColor()
            }
            else {
                self.backgroundColor = UIColor.clearColor()
            }

        }
    }

}
like image 24
King-Wizard Avatar answered Nov 18 '22 03:11

King-Wizard