1. 程式人生 > >【iOS】UIPanGestureRecognizer拖拽手勢

【iOS】UIPanGestureRecognizer拖拽手勢

拖拽手勢UIPanGestureRecognizer是什麼?

拖拽手勢顧名思義就是拖拽。蘋果的官方文件是這樣描述的:


使用有道詞典翻譯後是這樣的:

UIPanGestureRecognizer UIGestureRecognizer的具體子類,尋找平移(拖)手勢。使用者必須按一個或多個手指在一個檢視時鍋。客戶端實現這個手勢識別器的操作方法可以問它當前翻譯和速度的姿態

我們只需要看明白關鍵詞語就可以了。我的直譯是UIPanGestureRecognizer是一個繼承與 UIGestureRecognizer 的實現平移拖動的手勢。永續需要一個或者多個手指在一個指定的檢視中拖動。客戶端可以獲取這個手勢當前的退拽位置(姿態)和速度。

這裡面有兩個我們需要注意的  translation 和  velocity  這也是後面我們實現拖拽需要使用的。

程式碼並不難,就是為了實現在螢幕中可以隨意拖拽一張圖片的移動。

先上效果圖:


左邊是程式啟動後的熊愛國,右邊是圖片拖動後的位置。

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong)UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	
	[self setMainImageView];
	// Do any additional setup after loading the view, typically from a nib.
}
/**
 *  設定需要顯示的圖片 並增加拖動手勢
 */
- (void)setMainImageView{
	self.imageView = [[UIImageView alloc] init];
	self.imageView.frame = CGRectMake(10, 200, 100, 100);
	self.imageView.image = [UIImage imageNamed:@"pantest.png"];
	self.imageView.userInteractionEnabled = YES;
	[self.view addSubview:self.imageView];
	
	UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognizer:)];
	[self.imageView addGestureRecognizer:pan];
}
/**
 *  實現拖動手勢方法
 *
 *  @param panGestureRecognizer 手勢本身
 */
- (void)panGestureRecognizer:(UIPanGestureRecognizer *)panGestureRecognizer{
	//獲取拖拽手勢在self.view 的拖拽姿態
	CGPoint translation = [panGestureRecognizer translationInView:self.view];
	//改變panGestureRecognizer.view的中心點 就是self.imageView的中心點
	panGestureRecognizer.view.center = CGPointMake(panGestureRecognizer.view.center.x + translation.x, panGestureRecognizer.view.center.y + translation.y);
	//重置拖拽手勢的姿態
	[panGestureRecognizer setTranslation:CGPointZero inView:self.view];
}
- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

@end
手勢拖動的方法中為什麼這麼處理,還是看看官方怎麼說:


我的翻譯:使用者可以在它的操作(拖拽)方法裡面查詢UIPanGestureRecognizer物件的當前姿態和移動速度。使用者可以在指定的檢視的座標系統裡面應用當前的姿態和移動速度,使用者也可以重置姿態所需要的值。