Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom UIButton not highlighting when touched

I have a method that creates a custom UIButton that allows me to change the color of the button using QuartzCore. But the buttons don't highlight when touched.

- (UIButton *)makeHeaderButton {     UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];     UIFont *textFont = [UIFont boldSystemFontOfSize:12];     UIColor *textColor = [UIColor colorWithRed:80/255.0 green:109/255.0 blue:145/255.0 alpha:1.0];     UIColor *backgroundColor = [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1.0];     [button setTitleColor:textColor forState:UIControlStateNormal];     button.titleLabel.font = textFont;     button.autoresizesSubviews = YES;     button.layer.cornerRadius = 8;     button.layer.borderWidth = 1;     // next 2 properties set using QuartzCore class, no other way to set button colors     button.layer.borderColor = [UIColor grayColor].CGColor;     button.layer.backgroundColor = backgroundColor.CGColor;     button.clipsToBounds = YES;     return button; } 

How can I make these buttons highlight like a regular round rect button?

like image 216
Bob Avatar asked Dec 30 '12 02:12

Bob


2 Answers

In Swift, you can also override the isHighlighted var and add an alpha animation on it.

override var isHighlighted: Bool {     didSet {         UIView.animate(withDuration: 0.25, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction], animations: {             self.alpha = self.isHighlighted ? 0.5 : 1         }, completion: nil)     } } 
like image 178
GrizzlyBear Avatar answered Sep 24 '22 10:09

GrizzlyBear


In your code, add the line button.showsTouchWhenHighlighted = TRUE;

like image 23
Garrett Avatar answered Sep 21 '22 10:09

Garrett