UIGestureRecognizer是一个定义基本手势的抽象类:
1、拍击UITapGestureRecognizer (任意次数的拍击)
2、向里或向外捏UIPinchGestureRecognizer (用于缩放)
3、摇动或者拖拽UIPanGestureRecognizer (拖动)
4、擦碰UISwipeGestureRecognizer (以任意方向)
5、旋转UIRotationGestureRecognizer (手指朝相反方向移动)
6、长按UILongPressGestureRecognizer (长按)
1 首先建立一个要拖动的控件
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
btn.backgroundColor = [UIColor redColor];
[self.view addSubview:btn];
2 添加拖动手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];//创建手势
[btn setUserInteractionEnabled:YES]; //设置启用用户交互
[btn addGestureRecognizer:pan];//把手势添加到控件
- (void) handlePan: (UIPanGestureRecognizer *)rec{
// NSLog(@"xxoo---xxoo---xxoo");
CGPoint point = [rec translationInView:self.view];
//该方法返回在横坐标上、纵坐标上拖动了多少像素
NSLog(@"%f,%f",point.x,point.y);
rec.view.center = CGPointMake(rec.view.center.x + point.x, rec.view.center.y + point.y);
//rec.view 指的是把rec添加到那个控件上的
// 因为拖动起来一直是在递增,所以每次都要用setTranslation:方法制0这样才不至于不受控制般滑动出视图
[rec setTranslation:CGPointMake(0, 0) inView:self.view];
}
3添加缩放手势
//缩放
UIPinchGestureRecognizer *ping = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
[btn setUserInteractionEnabled:YES]; //设置启用用户交互
[btn addGestureRecognizer:ping];
-(void) handlePinch:(UIPinchGestureRecognizer *)rec
{
NSLog(@" recognizer.scale------%f",rec.scale
);//缩放的倍数,
// view.transform 为原来的 状态;
rec.view.transform=CGAffineTransformScale(rec.view.transform, rec.scale,rec.scale);
}
网友评论