0

我有一个按钮,我想“按住”按钮,这样它将继续打印“长按”,直到我释放按键。

我在 ViewDidLoad 中有这个:

[self.btn addTarget:self action:@selector(longPress:) forControlEvents:UIControlEventTouchDown];

- (void)longPress: (UILongPressGestureRecognizer *)sender {
    if (sender.state == UIControlEventTouchDown) {
      NSLog(@"Long Press!");
    }
}

我也试过这个:

 UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
 lpgr.minimumPressDuration = 0.1;
 lpgr.numberOfTouchesRequired = 1;
 [self.btn addGestureRecognizer:lpgr];

它只打印出长按!即使我按住按钮一次。谁能告诉我哪里做错了或者我错过了什么?谢谢!

4

1 回答 1

2

首先,UIButton的目标-动作对回调仅在相应事件触发时执行一次。

UILongPressGestureRecognizer需要一个minimumPressDuration才能进入UIGestureRecognizerStateBegan状态,然后当手指移动时,回调将触发UIGestureRecognizerStateChanged状态。最后,释放手指时的UIGestureRecognizerStateEnded状态。

按下按钮时,您的要求会反复触发。一流的都不能满足您的需求。相反,您需要在按钮按下时设置一个重复触发计时器,并在按钮释放时释放它。

所以代码应该是:

    [btn addTarget:self action:@selector(touchBegin:) forControlEvents: UIControlEventTouchDown];
    [btn addTarget:self action:@selector(touchEnd:) forControlEvents:
        UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel];

- (void)touchBegin:(UIButton*)sender {
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(longPress:) userInfo:nil repeats:YES];
}

- (void)touchEnd:(UIButton*)sender {
    [_timer invalidate];
    _timer = nil;
}

- (void)longPress:(NSTimer*)timer {
    NSLog(@"Long Press!");
}

顺便说一句,UIButtonUILongPressGestureRecognizer都没有UIControlEvents类型的状态

于 2016-01-07T13:09:14.663 回答