UIButton按住

use*_*008 4 uibutton ios

我想实现一个按住按钮.因此,当您按下按钮时,功能A执行,当您释放时,功能B执行.我找到了这个,但这不是我想要的.

UIButton触摸并保持

我不想要任何重复动作.

sud*_*-rf 22

只需UIButton根据不同的事件添加不同的选择器.要在最初按下时设置选择器,请执行以下操作

[button addTarget:self action:@selector(buttonDown:) forControlEvents:UIControlEventTouchDown];
Run Code Online (Sandbox Code Playgroud)

以及释放按钮时的选择器:

[button addTarget:self action:@selector(buttonUp:) forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)


Ash*_*ish 19

我自己也遇到过这个问题,大多数情况下我们都会使用这些事件: -

// 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];
Run Code Online (Sandbox Code Playgroud)

解:

使用长按手势识别器:

UILongPressGestureRecognizer *btn_LongPress_gesture = [[UILongPressGestureRecognizer alloc] 
        initWithTarget:self action:@selector(handleBtnLongPressGesture:)];
[button addGestureRecognizer:btn_LongPress_gesture];
Run Code Online (Sandbox Code Playgroud)

手势的实现: -

- (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];
  }
}
Run Code Online (Sandbox Code Playgroud)