最近在处理一些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;
}