最近在处理一些iOS相关的手势,早期的用法是使用UIView自带的一些touch事件:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
然后计算点击了哪里,手指移动的方向等等,最后计算出图片平移的位置,旋转的角度,放缩的程度。
好吧,这种方法简直是太弱了。
最方便的处理手势的方法是使用UIGestureRecognizer相关类:
分别处理点击,放缩,旋转,滑动,拖动和长按。
这些类都很容易使用,但今天我遇到了一个问题,就是能不能让一个界面同时响应放缩,旋转,滑动这三个不同的动作呢。
答案是肯定的,具体的做法就是将self设置为上面类对象的delegate,然后实现代理方法:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer
{
returnYES;
}
这样就可以同时响应了。
但还有一个问题,就是界面的跟着变化呢?
下面是具体实现:
- (void)twoFingerPan:(UIGestureRecognizer *)gestureRecognizer
{
switch (gestureRecognizer.state)
{
caseUIGestureRecognizerStateChanged:
{
_point = [(UIPanGestureRecognizer *)gestureRecognizer translationInView:self.view];
_scrollView.transform = CGAffineTransformMake(cosf(_rotation) * _scale, sinf(_rotation) * _scale, -sinf(_rotation) * _scale, cosf(_rotation) * _scale, _point.x, _point.y);
}
break;
default:
break;
}
}
- (void)twoFingerRotation:(UIGestureRecognizer *)gestureRecognizer
{
switch (gestureRecognizer.state)
{
caseUIGestureRecognizerStateChanged:
{
_rotation = [(UIRotationGestureRecognizer *)gestureRecognizer rotation];
_scrollView.transform = CGAffineTransformMake(cosf(_rotation) * _scale, sinf(_rotation) * _scale, -sinf(_rotation) * _scale, cosf(_rotation) * _scale, _point.x, _point.y);
}
break;
default:
break;
}
}
- (void)twoFingerPinch:(UIGestureRecognizer *)gestureRecognizer
{
switch (gestureRecognizer.state)
{
caseUIGestureRecognizerStateChanged:
{
_scale = [(UIPinchGestureRecognizer *)gestureRecognizer scale];
_scrollView.transform = CGAffineTransformMake(cosf(_rotation) * _scale, sinf(_rotation) * _scale, -sinf(_rotation) * _scale, cosf(_rotation) * _scale, _point.x, _point.y);
}
break;
default:
break;
}
手势识别与界面交互优化
本文探讨了在iOS应用中,如何从基本的触摸事件处理升级到使用UIGestureRecognizer类来更高效地处理手势,包括点击、放缩、旋转、滑动和长按等操作。重点介绍了如何实现代理方法,使界面能够同时响应多种手势,以及通过统一实现对View的transform属性调整界面变化。提供了解决方案,帮助开发者提升应用的手势交互体验。
6495

被折叠的 条评论
为什么被折叠?



