对于不能addTarget的UI对象,添加手势为他们带来了“福音”,以为UIView添加手势为例,揭开手势的面目。
1,创建一个view先,
UIView * jrView=[[UIViewalloc] initWithFrame:CGRectMake(0, 0, 160, 160)]; jrView.center=self.view.center; jrView.backgroundColor=[UIColorgreenColor]; [self.viewaddSubview:jrView];
2,添加手势
常用的手势:点击、长按、扫一下(表面滑过)、拖动、旋转、捏合。。
①:点击
首先,定义点击手势,然后设置手势的相关属性(点击次数、接触点的个数。。),最后将手势添加到view上即可。
点击了view就执行手势的@selector(tapGestureAction:)方法(所有的手势都是这样);
/** --点击-- */ UITapGestureRecognizer * tap=[[UITapGestureRecognizeralloc] initWithTarget:selfaction:@selector(tapGestureAction:)]; //-=--点击次数 tap.numberOfTapsRequired=2; //=-=-=触碰点的个数 tap.numberOfTouchesRequired=2; //tap.numberOfTouches; readOnly [jrView addGestureRecognizer:tap];
②:长按
定义手势
属性:算是长按的区域,算是长按的时间
添加手势到view
/** --长按-- */ UILongPressGestureRecognizer * lPress=[[UILongPressGestureRecognizeralloc] initWithTarget:selfaction:@selector(longPressAction:)]; //===--=长按的识别区域(在这里面即使移动了,算长按) lPress.allowableMovement=10; //=-=-==-按的时间-(按多久算长按) lPress.minimumPressDuration=0.5; [jrView addGestureRecognizer:lPress];
③:拖动
就是这么简洁;
/** 拖动 */ UIPanGestureRecognizer * pan=[[UIPanGestureRecognizeralloc] initWithTarget:selfaction:@selector(panAction:)]; [jrView addGestureRecognizer:pan];
④:轻扫(表面滑过)
可以设置滑过的方向,不同的方向触发不同的事件;
/** 轻扫 */ UISwipeGestureRecognizer * swipe=[[UISwipeGestureRecognizeralloc] initWithTarget:selfaction:@selector(swipeAction:)]; swipe.direction=UISwipeGestureRecognizerDirectionLeft; [jrView addGestureRecognizer:swipe];
⑤: 旋转
竟然有代理,请查看代理协议;
/** 旋转 */ UIRotationGestureRecognizer * rotation=[[UIRotationGestureRecognizeralloc] initWithTarget:selfaction:@selector(rotationAction:)]; rotation.delegate=self; [jrView addGestureRecognizer:rotation];
⑥: 捏合
要捏合的话,两个手指操作(合情合理);
/** 捏合 */ UIPinchGestureRecognizer * pinch=[[UIPinchGestureRecognizeralloc] initWithTarget:selfaction:@selector(pinchAction:)]; pinch.delegate=self; [jrView addGestureRecognizer:pinch];
同时,还可以设置同一个view响应多个手势,所以有了手势的delegate;
#pragma mark - 代理方法,使操作对象响应多个手势 - (BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{ returnYES; }
手势? so easy!
时间: 2024-10-13 22:23:15