[英]UILongPressGestureRecognizer iOS for continuous action
我有一個按鈕,我想“按下並按住”按鈕,以便它將一直打印“ Long Press”,直到我釋放按鍵為止。
我在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的target-action對回調僅執行一次 。
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!");
}
順便說一句, UIButton和UILongPressGestureRecognizer都不具有UIControlEvents類型的狀態
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.