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

iOS 開發(71):長按手勢的實作與參數設定

編輯:iOS 開發綜合

前言

UILongPressGestureRecognizer 用來偵測使用者用手指按住螢幕某處不放的情形。它比 Tap 多了兩個關鍵參數:可按多久、手指移動多遠還算有效,兩者都直接影響手感。

程式碼實作

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    self.dummyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.dummyButton.frame = CGRectMake(0.0f, 0.0f, 100.0f, 37.0f);
    self.dummyButton.center = self.view.center;
    [self.dummyButton setTitle:@"注意我的位置" forState:UIControlStateNormal];
    [self.view addSubview:self.dummyButton];

    /* 建立長按手勢識別器 */
    self.longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc]
                                       initWithTarget:self
                                       action:@selector(handleLongPressGestures:)];

    /* 需要幾根手指觸碰螢幕,預設為 1 */
    self.longPressGestureRecognizer.numberOfTouchesRequired = 2;

    /* 手勢被認定前,手指最多可移動 100 像素 */
    self.longPressGestureRecognizer.allowableMovement = 100.0f;

    /* 按住多久才算長按,單位為秒 */
    self.longPressGestureRecognizer.minimumPressDuration = 1.0;

    [self.view addGestureRecognizer:self.longPressGestureRecognizer];
}

- (void) handleLongPressGestures:(UILongPressGestureRecognizer *)paramSender{
    if ([paramSender isEqual:self.longPressGestureRecognizer]){
        // 手指數為 2 時,把按鈕移到兩指中點
        if (paramSender.numberOfTouchesRequired == 2){

            /******** 取得兩指中點 Start ********/
            CGPoint touchPoint1 = [paramSender locationOfTouch:0 inView:paramSender.view];
            CGPoint touchPoint2 = [paramSender locationOfTouch:1 inView:paramSender.view];

            CGFloat midPointX = (touchPoint1.x + touchPoint2.x) / 2.0f;
            CGFloat midPointY = (touchPoint1.y + touchPoint2.y) / 2.0f;
            CGPoint midPoint = CGPointMake(midPointX, midPointY);
            /******** 取得兩指中點 End ********/

            self.dummyButton.center = midPoint;
        }
    }
}

運行結果

初始畫面

雙指長按後,按鈕被移到兩指中點(模擬器中可用 Option +滑鼠模擬)

參數怎麼調

  • minimumPressDuration:按住秒數門檻。設 0.5 會感覺「按一下就觸發」,設 2.0 則需要明確停留。
  • allowableMovement:容許的移動像素。設太小會導致手抖就失敗,設太大又會讓拖曳也被誤判為長按。
  • numberOfTouchesRequired:多指長按常用於進階操作,但要多留意使用者的可發現性。

另外提醒:長按手勢在 UIGestureRecognizerStateBegan 之後還會持續回呼,若要只在「剛成立」或「結束」時處理一次,記得加上 state 判斷,避免同一段邏輯被連續執行。

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