手势在iOS开发中是一个比较常用的功能,不过相对来说大家用的比较少,经常刷网易新闻,上次用了一下捏合手势才发现可以调整字体大小。昨天看到一个介绍摇一摇这个功能的,没看到之前一直都觉得摇一摇是微信的专有的,昨天测试了一下知乎,感觉像发现了一个新大陆,随便截了图,效果如下:
扯的有点远了,很多应用的很多功能其实对于大多数而言是没有用到的,不过作为程序员我们还是应该多研究一下。
基础概念
常见的手势有六种,如下图所示:
UITapGestureRecognizer(点击,轻触摸)、UIPinchGestureRecognizer(二指往內或往外拨动,捏合手势)、UIPanGestureRecognizer(拖移)、UISwipeGestureRecognizer(滑动,快速移动)、UIRotationGestureRecognizer(旋转)和UILongPressGestureRecognizer(长按),由于微信的缘故应该大多数人对长按比较熟悉,Tap点击也是高频用到的手势。
苹果官方给出了Tap和Pinch的手势的效果图,其他的效果可以私下试一试:
Demo实战
由于有六种手势,基本上大同小异,其中一种会实战,其他的应该也没问题,接下来的的介绍都是以UITapGestureRecognizer为基准的,先来个简单的单击手势:
1
2
3
4
|
UITapGestureRecognizer *oneTapGestureReognizer = [[UITapGestureRecognizer alloc] initWithTarget:
self
action:
@selector
(oneTapGestureRecognizer:)];
oneTapGestureReognizer.delegate =
self
;
oneTapGestureReognizer.numberOfTapsRequired = 1;
//触摸次数
[
self
.view addGestureRecognizer:oneTapGestureReognizer];
|
响应事件:
1
2
3
4
|
-(
void
)oneTapGestureRecognizer:(UITapGestureRecognizer *)tapGestureRecognizer{
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@
"单指单击"
message:@
"iOS技术交流群:228407086"
delegate:
self
cancelButtonTitle:@
"确定"
otherButtonTitles:@
"取消"
,
nil
];
[alertView show];
}
|
效果如下:
单击手势显得稍微有点弱,我们可以继续修改手指和触摸的次数,来个双指双击看下代码:
1
2
3
4
5
|
UITapGestureRecognizer *twoTapGestureReognizer = [[UITapGestureRecognizer alloc] initWithTarget:
self
action:
@selector
(twoTapGestureRecognizer:)];
twoTapGestureReognizer.delegate =
self
;
twoTapGestureReognizer.numberOfTouchesRequired =2;
//手指数
twoTapGestureReognizer.numberOfTapsRequired=2;
//触摸次数
[
self
.view addGestureRecognizer:twoTapGestureReognizer];
|
响应事件如下:
1
2
3
4
|
-(
void
)twoTapGestureRecognizer:(UITapGestureRecognizer *)tapGestureRecognizer{
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@
"手势点击"
message:@
"iOS技术交流群:228407086"
delegate:
self
cancelButtonTitle:@
"确定"
otherButtonTitles:@
"取消"
,
nil
];
[alertView show];
}
|
效果就不需要截图了,基本上UITapGestureRecognizer点击差不多就是设置一下手指数量和触摸次数,不过有的时候会出现同一个View上需要手势,按钮需要点击,就是事件被覆盖,需要通过UIGestureRecognizerDelegate中的方法防止事件覆盖。
1
2
3
4
5
6
7
|
-(
BOOL
)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
//设置为NO则不响应
if
([
NSStringFromClass
([touch.view
class
]) isEqualToString:@
"UILabel"
]) {
return
NO
;
}
return
YES
;
}
|
上面的代码是为了让截图上的标签不响应触摸的事件,标签其实默认的是没有点击响应事件的,我们可以在标签上面加入触摸事件:
1
2
3
4
5
|
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(10, 44, 380, 30)];
label.text=@
"原文地址:http://www.cnblogs.com/xiaofeixiang"
;
[label setUserInteractionEnabled:
YES
];
[label addGestureRecognizer:tapGestureRecognizer];
[
self
.view addSubview:label];
|
响应事件:
1
2
3
4
5
|
-(
void
)tapJumpLink:(UITapGestureRecognizer *)tapGestureRecognizer{
UILabel *label=(UILabel *)tapGestureRecognizer.view;
NSURL
*url=[[
NSURL
alloc]initWithString:[label.text substringFromIndex:5]];
[[UIApplication sharedApplication] openURL:url];
}
|
最终效果如下:
本文转自Fly_Elephant博客园博客,原文链接:http://www.cnblogs.com/xiaofeixiang/p/4584175.html,如需转载请自行联系原作者