UILongPressGestureRecognizer iOS用于持续行动

时间:2015-12-11 18:48:14

标签: ios xcode gesture uilongpressgesturerecogni

我有一个按钮,我想"按下并按住"按钮,这样它将继续打印"长按"直到我发布按键。

我在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];

它只打印长按!甚至当我按下按钮时。 谁能告诉我我做错了什么或我错过了什么? 谢谢!

1 个答案:

答案 0 :(得分:2)

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

UILongPressGestureRecognizer 需要 minimumPressDuration 进入 UIGestureRecognizerStateBegan 状态,然后当手指移动时,将使用 UIGestureRecognizerStateChanged <来触发回调/ strong>州。释放手指时, 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!");
}

顺便说一下, UIButton UILongPressGestureRecognizer 都没有类型 UIControlEvents

的状态