检测何时按下自定义UIButton

时间:2020-12-10 21:10:23

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.)

我为我的应用程序创建了一个自定义UIButton(UIButton子类)。在此按钮的实现中,如何在按下时更改背景颜色? (它在郁闷时应恢复正常背景。我目前正在使用Core Graphics绘制渐变背景。)

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.

我试过在drawRect中进行分支:(检查self.selected和self.highlighted,但是没有发生变化,因为在触摸事件上没有调用drawRect。

Any suggestions or code samples are appreciated.

任何建议或代码示例表示赞赏。

1 个解决方案

#1


15  

Try calling [self setNeedsRedraw] in your touch event.

尝试在触摸事件中调用[self setNeedsRedraw]。


Asker provided a solution based on this answer and the comments below.

Asker根据此答案和以下评论提供了解决方案。

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.

选择器是执行后台更改的自定义函数。

#1


15  

Try calling [self setNeedsRedraw] in your touch event.

尝试在触摸事件中调用[self setNeedsRedraw]。


Asker provided a solution based on this answer and the comments below.

Asker根据此答案和以下评论提供了解决方案。

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.

选择器是执行后台更改的自定义函数。