答案 0 :(得分:22)
只需根据不同的事件向UIButton
添加不同的选择器即可。要在最初按下时设置选择器,请执行以下操作
[button addTarget:self action:@selector(buttonDown:) forControlEvents:UIControlEventTouchDown];
以及释放按钮时的选择器:
[button addTarget:self action:@selector(buttonUp:) forControlEvents:UIControlEventTouchUpInside];
答案 1 :(得分:18)
我自己也遇到过这个问题,主要是我们使用这些事件: -
// This event works fine and fires
[button addTarget:self action:@selector(holdDown)
forControlEvents:UIControlEventTouchDown];
// This does not fire at all
[button addTarget:self action:@selector(holdRelease)
forControlEvents:UIControlEventTouchUpInside];
解决方案:
使用长按手势识别器:
UILongPressGestureRecognizer *btn_LongPress_gesture = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleBtnLongPressGesture:)];
[button addGestureRecognizer:btn_LongPress_gesture];
手势的实现: -
- (void)handleBtnLongPressGesture:(UILongPressGestureRecognizer *)recognizer {
//as you hold the button this would fire
if (recognizer.state == UIGestureRecognizerStateBegan) {
[self buttonDown];
}
// as you release the button this would fire
if (recognizer.state == UIGestureRecognizerStateEnded) {
[self buttonUp];
}
}
答案 2 :(得分:3)
你可以实施
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
方法
然后使用CGRectContainsPoint()
然后如果用户移动手指
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
将被调用。在那里你应该再次检查用户是否仍然在你的按钮上。否则停止你的功能
和
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
用户从屏幕上移开手指时会调用
答案 3 :(得分:1)
我认为最好的解决方案是使用UIGestureRecognizer实现,其中一个是UITapGestureRecognizer,另一个是UILongPressGestureRecognizer
答案 4 :(得分:0)
UILongPressGestureRecognizer Swift 3及更高版本:
// Add Gesture Recognizer to view
let longPressGestureRecognizer = UILongPressGestureRecognizer(
target: self,
action: #selector(handleLongPress(_:)))
view.addGestureRecognizer(longPressGestureRecognizer!)