您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

建立可拖曳 UIView 的實作思路

編輯:iOS 相關資訊

在 iOS 中,UIView 繼承自 UIResponder,因此可回應觸控事件。若要讓 view 可拖動,最常使用 touchesBegan:withEvent: 與 touchesMoved:withEvent:。

基本思路是:在 touchesBegan 記錄起始點,在 touchesMoved 計算位移,並更新 view 的 frame 或 center。

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

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint current = [touch locationInView:self];
    CGRect frame = self.frame;
    frame.origin.x += current.x - self.beginPoint.x;
    frame.origin.y += current.y - self.beginPoint.y;
    self.frame = frame;
}

若要避免 view 被拖出畫面,可在更新 center 後檢查父視圖邊界,並將 x、y 限制在可視範圍內。若希望拖曳結束後自動吸附到某個位置,則可再實作 touchesEnded:withEvent:。

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