How to change the background color of a UIButton while it's highlighted? How to change the background color of a UIButton while it's highlighted? ios ios

How to change the background color of a UIButton while it's highlighted?


You can override UIButton's setHighlighted method.

Objective-C

- (void)setHighlighted:(BOOL)highlighted {    [super setHighlighted:highlighted];    if (highlighted) {        self.backgroundColor = UIColorFromRGB(0x387038);    } else {        self.backgroundColor = UIColorFromRGB(0x5bb75b);    }}

Swift 3.0 and Swift 4.1

override open var isHighlighted: Bool {    didSet {        backgroundColor = isHighlighted ? UIColor.black : UIColor.white    }}


Not sure if this sort of solves what you're after, or fits with your general development landscape but the first thing I would try would be to change the background colour of the button on the touchDown event.

Option 1:

You would need two events to be capture, UIControlEventTouchDown would be for when the user presses the button. UIControlEventTouchUpInside and UIControlEventTouchUpOutside will be for when they release the button to return it to the normal state

UIButton *myButton =  [UIButton buttonWithType:UIButtonTypeCustom];[myButton setFrame:CGRectMake(10.0f, 10.0f, 100.0f, 20.f)];[myButton setBackgroundColor:[UIColor blueColor]];[myButton setTitle:@"click me:" forState:UIControlStateNormal];[myButton setTitle:@"changed" forState:UIControlStateHighlighted];[myButton addTarget:self action:@selector(buttonHighlight:) forControlEvents:UIControlEventTouchDown];[myButton addTarget:self action:@selector(buttonNormal:) forControlEvents:UIControlEventTouchUpInside];

Option 2:

Return an image made from the highlight colour you want. This could also be a category.

+ (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;}

and then change the highlighted state of the button:

[myButton setBackgroundImage:[self imageWithColor:[UIColor greenColor]] forState:UIControlStateHighlighted];


There is no need to override highlighted as computed property. You can use property observer to trigger background color change:

override var highlighted: Bool {    didSet {        backgroundColor = highlighted ? UIColor.lightGrayColor() : UIColor.whiteColor()    }}

Swift 4

override open var isHighlighted: Bool {    didSet {        backgroundColor = isHighlighted ? UIColor.lightGray : UIColor.white    }}