I have created a custom UIButton (UIButton subclass) for my application. Within this button's implementation, how would I alter the background color when it is pressed? (It should revert to it's normal background when depressed. I am currently using Core Graphics to draw a gradient background.)
I have tried branching in drawRect: (checking for self.selected and self.highlighted, but no change occurs because drawRect is not being called on the touch event.
Any suggestions or code samples are appreciated.
You can use the following code. class ViewController: UIViewController { var gameTimer: Timer! @IBAction func btnClick(_ sender: Any) { let button = UIButton() if (button. isSelected) { print(" Not Selected"); } else { print(" Selected"); } } override func viewDidLoad() { super.
Try calling [self setNeedsRedraw] in your touch event.
Asker provided a solution based on this answer and the comments below.
Solution
Used:
[self addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchDown];
[self addTarget:self action:@selector(buttonDepressed) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel];
Where the selectors are custom functions that perform the background change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With