Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting when a custom UIButton has been pressed

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.

like image 514
Evan Mulawski Avatar asked Oct 26 '11 21:10

Evan Mulawski


People also ask

How can I check if UIButton is pressed?

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.


1 Answers

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.

like image 171
Micah Hainline Avatar answered Sep 20 '22 19:09

Micah Hainline