我正在檢測用戶是否已按下2秒鐘: ui
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; longPress.minimumPressDuration = 2.0; [self addGestureRecognizer:longPress]; [longPress release];
這是我處理長按的方式: spa
-(void)handleLongPress:(UILongPressGestureRecognizer*)recognizer{ NSLog(@"double oo"); }
當我按下2秒鐘以上時,文本「 double oo」被打印兩次。 爲何是這樣? 我該如何解決? code
您的手勢處理程序會收到每種手勢狀態的呼叫。 所以,您須要檢查每一個狀態並將代碼置於必需狀態。 事件
必須使用switch-case而不是if-else: get
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; longPress.minimumPressDuration = 1.0; [myView addGestureRecognizer:longPress]; [longPress release];
-(void)handleLongPress:(UILongPressGestureRecognizer *)gesture { switch(gesture.state){ case UIGestureRecognizerStateBegan: NSLog(@"State Began"); break; case UIGestureRecognizerStateChanged: NSLog(@"State changed"); break; case UIGestureRecognizerStateEnded: NSLog(@"State End"); break; default: break; } }
這是在Swift中處理的方法: it
func longPress(sender:UILongPressGestureRecognizer!) { if (sender.state == UIGestureRecognizerState.Ended) { println("Long press Ended"); } else if (sender.state == UIGestureRecognizerState.Began) { println("Long press detected."); } }
Objective-C的 io
- (void)handleLongPress:(UILongPressGestureRecognizer*)sender { if (sender.state == UIGestureRecognizerStateEnded) { NSLog(@"Long press Ended"); } else if (sender.state == UIGestureRecognizerStateBegan) { NSLog(@"Long press detected."); } }
Swift 2.2: select
func handleLongPress(sender:UILongPressGestureRecognizer) { if (sender.state == UIGestureRecognizerState.Ended) { print("Long press Ended"); } else if (sender.state == UIGestureRecognizerState.Began) { print("Long press detected."); } }
UILongPressGestureRecognizer是連續事件識別器。 您必須查看狀態以查看這是事件的開始,中間仍是結束,並採起相應的措施。 即,您能夠在開始以後放棄全部事件,或者僅根據須要查看運動。 從類參考 : bug
長按手勢是連續的。 當在指定時間段內(minimumPressDuration)按下了容許的手指數(numberOfTouchesRequired),而且觸摸沒有移動超出容許的移動範圍(allowableMovement)時,手勢即開始(UIGestureRecognizerStateBegan)。 每當手指移動時,手勢識別器都會轉換爲「更改」狀態,而且在任何手指擡起時手勢識別器都會終止(UIGestureRecognizerStateEnded)。 程序
如今您能夠像這樣跟蹤狀態
- (void)handleLongPress:(UILongPressGestureRecognizer*)sender { if (sender.state == UIGestureRecognizerStateEnded) { NSLog(@"UIGestureRecognizerStateEnded"); //Do Whatever You want on End of Gesture } else if (sender.state == UIGestureRecognizerStateBegan){ NSLog(@"UIGestureRecognizerStateBegan."); //Do Whatever You want on Began of Gesture } }
Swift 3.0:
func handleLongPress(sender: UILongPressGestureRecognizer) { if sender.state == .ended { print("Long press Ended") } else if sender.state == .began { print("Long press detected") }