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

iOS 可拖動 View 的原理與實作:從基礎版到邊界約束版

編輯:iOS 開發綜合

浮動視窗、可拖曳的懸浮按鈕、備忘貼紙……這些互動背後都是同一個原理:攔截觸控事件,依手指位移更新 view 的 frame 或 center。由於 UIView 繼承自 UIResponder,它天生就能回應觸控相關事件,因此實作門檻並不高。

關鍵的四個方法

  • -touchesBegan:withEvent::手指按下,通常在此記錄起始座標
  • -touchesMoved:withEvent::手指移動,主要邏輯都在這裡
  • -touchesEnded:withEvent::手指離開。若需要「自動吸附到邊緣」之類的效果,就實作這個方法
  • -touchesCancelled:withEvent::觸控被系統中斷(來電、通知等),需要額外善後時使用

前兩個方法是拖動功能的必要條件;後兩個則視需求而定,只做基本拖曳可以不實作。

兩種常見的思路

思路一:自訂 UIView 子類。把觸控邏輯寫進 view 自己,封裝性最好,同一個元件放到哪都能拖。

思路二:寫在 view controller 中。由 controller 持有要拖動的 view 並實作觸控方法。這種做法的好處是可以集中管理多個可拖動元素,但要注意:此時接收觸控的範圍會變成整個 controller 的根 view,因此必須在 touchesBegan: 中判斷手指是否落在目標 view 上(可從 UITouch 取得 view 屬性)。

兩者都可行,依實際架構選擇即可。

基礎版:子類實作

@interface TouchDragView ()
@property (assign, nonatomic) CGPoint beginPoint;
@end

@implementation TouchDragView

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    self.beginPoint = [touch locationInView:self];
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint currentLocation = [touch locationInView:self];

    CGRect frame = self.frame;
    frame.origin.x += currentLocation.x - self.beginPoint.x;
    frame.origin.y += currentLocation.y - self.beginPoint.y;
    self.frame = frame;
}

@end

這段程式碼可以拖,但有個明顯缺陷:view 會被拖到螢幕外面去,看不見也拿不回來。要解決這個問題,就需要在移動時加上邊界判斷。

進階版:加入螢幕邊界約束

以下版本以 view controller 為實作基礎(未子類化 view),self.localView 是你要拖動的小視窗,beginPoint 與 isInView 需在 controller 中自行宣告。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];

    // 僅當手指落在小視窗上時才響應拖動(此處以寬度 120 做簡易判斷,實務上建議用 tag 或 view 比較)
    if (touch.view.frame.size.width == 120) {
        self.isInView = YES;
    } else {
        self.isInView = NO;
    }

    beginPoint = [touch locationInView:self.localView];
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (!self.isInView) {
        return;
    }

    UITouch *touch = [touches anyObject];
    CGPoint currentPosition = [touch locationInView:self.localView];

    // 計算位移量
    CGFloat offsetX = currentPosition.x - beginPoint.x;
    CGFloat offsetY = currentPosition.y - beginPoint.y;

    // 更新中心座標
    self.localView.center = CGPointMake(self.localView.center.x + offsetX,
                                        self.localView.center.y + offsetY);

    UIView *superview = self.localView.superview;
    CGFloat halfW = self.localView.frame.size.width / 2.0;
    CGFloat halfH = self.localView.frame.size.height / 2.0;

    // X 軸左右極限
    if (self.localView.center.x > superview.frame.size.width - halfW) {
        self.localView.center = CGPointMake(superview.frame.size.width - halfW,
                                            self.localView.center.y);
    } else if (self.localView.center.x < halfW) {
        self.localView.center = CGPointMake(halfW, self.localView.center.y);
    }

    // Y 軸上下極限
    if (self.localView.center.y > superview.frame.size.height - halfH) {
        self.localView.center = CGPointMake(self.localView.center.x,
                                            superview.frame.size.height - halfH);
    } else if (self.localView.center.y <= halfH) {
        self.localView.center = CGPointMake(self.localView.center.x, halfH);
    }
}

幾個可以更好的細節

用 tag 取代硬編碼寬度。以 touch.view.frame.size.width == 120 判斷目標,只要元件尺寸一改就會失效。改用 touch.view == self.localView 或 tag 比對會穩健得多。

改用 UIPanGestureRecognizer。手勢識別器能自動處理 touchesCancelled、多指判斷等邊界情況,程式碼也更短。在 gesture 的 handler 中用 translationInView: 取位移即可。

記得處理旋轉與多螢幕。邊界計算若使用固定數值,在裝置旋轉後就會出錯。以 superview 的 bounds 為基準,並在 layoutSubviews 中重新夾住位置,會更可靠。

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