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

iOS 開發(70):用 UIPanGestureRecognizer 實作拖拽

編輯:iOS 開發綜合

前言

拖曳是行動裝置上最直覺的操作。以 UIPanGestureRecognizer 搭配 locationInView:,幾行程式碼就能讓任何視圖跟著手指跑。

程式碼實作

@synthesize helloWorldLabel;
@synthesize panGestureRecognizer;

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

    /* 先建立一個 label 作為拖曳對象 */
    CGRect labelFrame = CGRectMake(0.0f,   /* X */
                                   0.0f,   /* Y */
                                   150.0f, /* 寬 */
                                   100.0f);/* 高 */

    self.helloWorldLabel = [[UILabel alloc] initWithFrame:labelFrame];
    self.helloWorldLabel.text = @"Hello World";
    self.helloWorldLabel.backgroundColor = [UIColor blackColor];
    self.helloWorldLabel.textColor = [UIColor whiteColor];
    self.helloWorldLabel.textAlignment = NSTextAlignmentCenter;

    // UILabel 預設不接收觸摸,必須開啟互動屬性
    self.helloWorldLabel.userInteractionEnabled = YES;

    [self.view addSubview:self.helloWorldLabel];

    // 建立拖拽手勢
    self.panGestureRecognizer = [[UIPanGestureRecognizer alloc]
                                 initWithTarget:self
                                 action:@selector(handlePanGestures:)];

    // 最小與最大都設為 1,只允許單指拖曳
    self.panGestureRecognizer.minimumNumberOfTouches = 1;
    self.panGestureRecognizer.maximumNumberOfTouches = 1;

    [self.helloWorldLabel addGestureRecognizer:self.panGestureRecognizer];
}

- (void) handlePanGestures:(UIPanGestureRecognizer*)paramSender{
    if (paramSender.state != UIGestureRecognizerStateEnded
        && paramSender.state != UIGestureRecognizerStateFailed){
        // 以父視圖的座標系取得手勢位置,直接指派給 center
        CGPoint location = [paramSender locationInView:paramSender.view.superview];
        paramSender.view.center = location;
    }
}

運行結果

拖曳前

拖曳後

關鍵細節

  • 座標系要對齊:locationInView: 傳入的是 paramSender.view.superview,因為 center 是相對於父視圖的座標。這一步弄錯,視圖就會跑到莫名其妙的位置。
  • state 判斷:拖曳是連續手勢,會不斷回呼;排除 Ended 與 Failed,可避免放手後視圖又跳一下。
  • 手勢掛在哪裡:掛在視圖自身(如上例),只有碰到該視圖才會啟動;掛在父視圖上,則整片區域都能拖。可依需求選擇。
  • 延伸應用:搭配 translationInView: 做相對位移、加上慣性甩尾的 velocityInView:,或設定邊界限制,都能讓拖曳手感更自然。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved