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

iOS 實作左右拖曳抽屜:touchesMoved 與 KVO 的組合技

編輯:iOS 開發綜合

本文實作一個左右滑動的抽屜:手指跟著動,中間的主視圖會縮小並偏移,左右兩側的視圖則依方向自動切換顯示。核心技巧有三個——在 loadView 中預先佈局、用 touchesMoved 追蹤手指、再用 KVO 監聽 frame 變化決定要顯示哪一側。

為什麼用 KVO

抽屜的顯示邏輯取決於主視圖目前偏左還是偏右。若把這段判斷散落在每個改動 frame 的地方,很快就會難以維護。改為監聽 mainView 的 frame,讓「位置變化」自動觸發「該顯示哪一側」,職責就切乾淨了。

#import "DarwViewController.h"

@interface DarwViewController ()

@property (nonatomic, weak) UIView *leftView;
@property (nonatomic, weak) UIView *rightView;
@property (nonatomic, weak) UIView *mainView;

/** 動畫進行中,期間不處理 KVO 回呼 */
@property (nonatomic, assign) BOOL animating;

@end

@implementation DarwViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

// 在 self.view 載入之前就把三層視圖都準備好
- (void)loadView {
    self.view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];

    // 左側視圖
    UIView *leftView = [[UIView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:leftView];
    leftView.backgroundColor = [UIColor redColor];
    self.leftView = leftView;

    // 右側視圖
    UIView *rightView = [[UIView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:rightView];
    rightView.backgroundColor = [UIColor blueColor];
    self.rightView = rightView;

    // 主視圖(蓋在最上層)
    UIView *mainView = [[UIView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:mainView];
    mainView.backgroundColor = [UIColor yellowColor];
    self.mainView = mainView;

    // 監聽主視圖的 frame
    [self.mainView addObserver:self
                    forKeyPath:@"frame"
                       options:NSKeyValueObservingOptionNew
                       context:nil];
}

/**
 * 當 mainView 的 frame 改變時觸發
 */
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *, id> *)change
                       context:(void *)context {

    if (self.animating) return;   // 動畫期間跳過,避免與動畫互相打架

    if (self.mainView.frame.origin.x > 0) {
        // 主視圖右移 → 露出左側
        self.rightView.hidden = YES;
        self.leftView.hidden = NO;
    } else if (self.mainView.frame.origin.x < 0) {
        // 主視圖左移 → 露出右側
        self.leftView.hidden = YES;
        self.rightView.hidden = NO;
    }
}

#pragma mark - 觸摸事件

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

    CGPoint currentPoint  = [touch locationInView:self.view];
    CGPoint previousPoint = [touch previousLocationInView:self.view];

    // 這一幀在 x 方向的位移
    CGFloat offsetX = currentPoint.x - previousPoint.x;

    self.mainView.frame = [self rectWithOffsetX:offsetX];
}

#define screenW [UIScreen mainScreen].bounds.size.width
#define screenH [UIScreen mainScreen].bounds.size.height

/**
 * 依 x 位移計算新的 frame
 * 除了平移,還會依偏移量做縮放,做出「拉開時主視圖往後退」的景深效果
 */
- (CGRect)rectWithOffsetX:(CGFloat)offsetX {
    // y 方向的位移與 x 相關,偏移越多、上下留白越大
    CGFloat offsetY = (screenH * 1 / 5) * (offsetX / screenW);

    // 縮放比例:留白變多,視圖就變小
    CGFloat scale = (screenH - offsetY * 2) / screenH;

    // 若 x 為負(露出右側),比例要反過來算
    if (self.mainView.frame.origin.x < 0) {
        scale = 2 - scale;
    }

    CGRect frame = self.mainView.frame;

    // 限制最大尺寸,避免超出螢幕
    frame.size.width  = frame.size.width * scale  > screenW ? screenW  : frame.size.width * scale;
    frame.size.height = frame.size.height * scale > screenH ? screenH : frame.size.height * scale;

    frame.origin.x += offsetX;
    frame.origin.y  = (screenH - frame.size.height) * 0.5;   // 垂直居中

    return frame;
}

#define maxRightX (screenW * 0.8)    // 左側抽屜全開時的 x
#define maxLeftX  (-screenW * 0.6)   // 右側抽屜全開時的 x

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    CGFloat targetX = 0;

    // 主視圖大部分在右半邊 → 定位到左側抽屜
    if (self.mainView.frame.origin.x > screenW * 0.5) {
        targetX = maxRightX;
    }
    // 主視圖大部分在左半邊 → 定位到右側抽屜
    else if (CGRectGetMaxX(self.mainView.frame) < screenW * 0.5) {
        targetX = maxLeftX;
    }

    CGFloat offsetX = targetX - self.mainView.frame.origin.x;

    self.animating = YES;
    [UIView animateWithDuration:0.4 animations:^{
        if (targetX == 0) {
            // 復位
            self.mainView.frame = self.view.frame;
        } else {
            // 吸附到指定位置
            self.mainView.frame = [self rectWithOffsetX:offsetX];
        }
    } completion:^(BOOL finished) {
        self.animating = NO;
    }];
}

@end

三個值得注意的細節

animating 旗標為什麼必要。動畫執行的 0.4 秒內,frame 每幀都在變,KVO 會被連續觸發。此時去改 hidden 會造成左右視圖瘋狂閃爍。加一個旗標把動畫期間排除掉,問題就消失了。另外,dealloc 中別忘了 removeObserver:forKeyPath:。

為什麼在 loadView 而不是 viewDidLoad。loadView 是 view 被建立的直接責任歸屬,在這裡指定 self.view 並完成三層佈局,能確保後續任何程式碼拿到的都是最終狀態。

縮放比例的方向判斷。往右拖(offsetX > 0)時 mainView 變小;往左拖時 x 為負,若沿用同一公式會算出大於 1 的比例,所以用 2 - scale 反轉。這是這段程式最容易寫錯的地方。

實作上還可以補上 touchesCancelled 的處理(目前只有 touchesEnded),否則來電或手勢被系統攔截時,主視圖會停在半路。

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