您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 長按手勢觸發兩次的成因與修正

編輯:iOS 開發綜合

為 tableView 加上長按手勢之後,常會發現明明只是按住再放開,回呼方法卻執行了兩次。這其實不是 bug,而是 UILongPressGestureRecognizer 的設計使然。

問題重現

先為 tableView 註冊長按手勢:

UILongPressGestureRecognizer *longPressGr =
    [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
longPressGr.minimumPressDuration = 0.5f;
longPressGr.numberOfTouchesRequired = 1;
[_tableView addGestureRecognizer:longPressGr];
[longPressGr release];

回呼方法:

- (void)longPressAction:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        CGPoint point = [longPress locationInView:_tableView];

        // 取得長按位置落在哪個 cell 上
        NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:point];

        if (indexPath != nil) {
            NSLog(@"%ld", (long)indexPath.row);
        }
    }
}

原因

UILongPressGestureRecognizer 在整個按壓過程中會經歷多個狀態變化:UIGestureRecognizerStatePossible → UIGestureRecognizerStateBegan → 持續變化 → UIGestureRecognizerStateEnded。回呼方法在這些階段都會被呼叫,只是 state 不同。

所以「執行兩次」的真相是:一次是手指按滿 0.5 秒觸發 Began,另一次是手指離開時觸發 Ended。程式碼本身沒有問題,問題在於沒有依 state 過濾。

解法

只要確實判斷 state,就能讓業務邏輯只在該執行的時機跑一次。上面範例中已經用 if (longPress.state == UIGestureRecognizerStateBegan) 做了過濾,這就是正確做法。

若需要在按壓過程中持續追蹤(例如拖動選單),則可改成 switch 明確處理各階段:

- (void)longPressAction:(UILongPressGestureRecognizer *)longPress {
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan: {
            // 剛觸發長按,做初始化
            break;
        }
        case UIGestureRecognizerStateChanged: {
            // 手指移動中,更新位置
            break;
        }
        case UIGestureRecognizerStateEnded: {
            // 手指離開,收尾
            break;
        }
        default:
            break;
    }
}

順帶一提,透過 indexPathForRowAtPoint: 取得 nil 就代表長按落在空白處,實務上記得加這層判斷,否則後面取值會出錯。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved