拖拽手势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对象的当前姿态和移动速度。用户可以在指定的视图的坐标系统里面应用当前的姿态和移动速度,用户也可以重置姿态所需要的值。