gpt4 book ai didi

ios - UILongPressGestureRecognizer iOS 用于连续 Action

转载 作者:行者123 更新时间:2023-11-28 21:35:01 28 4
gpt4 key购买 nike

我有一个按钮,我想“按下并按住”按钮,这样它就会一直打印“长按”,直到我松开按键为止。

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

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

最佳答案

首先,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

的状态

关于ios - UILongPressGestureRecognizer iOS 用于连续 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34230510/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com