Custom UIButton not highlighting when touched
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) }}
If someone still encounters the problem - you should create UIButton like this:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];btn.layer.cornerRadius = 4;btn.layer.masksToBounds = YES;[btn setTranslatesAutoresizingMaskIntoConstraints:NO];[btn setBackgroundColor:[UIColor greenColor]];[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];[btn setTitle:@"ok" forState:UIControlStateNormal];*** any customisation that you would like ***[parentView addSubview: btn];
So this way you still have iOS taking care of all highlighting. The main thing is using
[UIButton buttonWithType:UIButtonTypeSystem];
If you use initWithFrame or any other method - you would have to implement
setTitleColor: forState: setBackgroundImage: forState: