简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM