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

iOS 開發中拖動視圖的實現方法詳解

編輯:iOS 開發綜合

預備知識

iOS 處理屏幕上的觸摸動作,主要涉及以下幾個方法:

touchesBegan:withEvent:       // 觸摸開始時調用
touchesMoved:withEvent:       // 移動過程中被調用
touchesEnded:withEvent:       // 動作結束時調用
touchesCancelled:withEvent:

從命名即可看出各方法的調用時機,其中最後一個較為特殊,它在 Cocoa Touch 必須響應持續觸摸事件的系統中斷時被調用。我們只需重寫這些方法來完成想要的行為。

如何實現拖動視圖?

1. 將 userInteractionEnabled 屬性設為 YES,允許使用者交互;
2. 在觸摸開始時記錄起始點;
3. 移動過程中計算當前座標與起始點的差值(偏移量),並將視圖中心點移至該偏移處;
4. 分別限制 x、y 座標,確保使用者無法將視圖拖出屏幕。

之所以要分別限制 x 與 y 座標,是因為即使向右拖不動了,仍需保證能繼續向下拖動。

基本寫法

1. 註冊拖動動畫(使用 UIPanGestureRecognizer):

UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(doHandlePanAction:)];
[self.vLight addGestureRecognizer:panGestureRecognizer];

其中 vLight 即為要加入拖動功能的視圖。

2. 拖動處理函數

- (void)doHandlePanAction:(UIPanGestureRecognizer *)paramSender{
    CGPoint point = [paramSender translationInView:self.view];
    paramSender.view.center = CGPointMake(paramSender.view.center.x + point.x, paramSender.view.center.y + point.y);
    [paramSender setTranslation:CGPointMake(0, 0) inView:self.view];
}

實現代碼

以下以子類化 UIImageView 為例:

#import <UIKit/UIKit.h>
@interface GragView : UIImageView
{
    CGPoint startPoint;
}
@end

#import "GragView.h"
@implementation GragView
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES; // 允許用戶交互
    }
    return self;
}
- (id)initWithImage:(UIImage *)image
{
    self = [super initWithImage:image];
    if (self) {
        self.userInteractionEnabled = YES;
    }
    return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 保存觸摸起始點位置
    CGPoint point = [[touches anyObject] locationInView:self];
    startPoint = point;
    // 將該 view 置於最前
    [[self superview] bringSubviewToFront:self];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 計算位移 = 當前位置 - 起始位置
    CGPoint point = [[touches anyObject] locationInView:self];
    float dx = point.x - startPoint.x;
    float dy = point.y - startPoint.y;
    // 計算移動後的 view 中心點
    CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy);
    // 限制用戶不可將視圖拖出屏幕
    float halfx = CGRectGetMidX(self.bounds);
    newcenter.x = MAX(halfx, newcenter.x); // x 左邊界
    newcenter.x = MIN(self.superview.bounds.size.width - halfx, newcenter.x); // x 右邊界
    float halfy = CGRectGetMidY(self.bounds);
    newcenter.y = MAX(halfy, newcenter.y); // y 同理
    newcenter.y = MIN(self.superview.bounds.size.height - halfy, newcenter.y);
    self.center = newcenter; // 移動 view
}
@end

整體思路清晰:記錄起始點、計算位移、更新中心點,並透過邊界判斷防止視圖被拖出屏幕可視範圍,便能實現流暢自然的拖動體驗。

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