我想检测从屏幕右下角到中间的双指对角线滑动。我尝试添加方向设置为“UISwipeGestureRecognizerDirectionUp | UISwipeGestureRecognizerDirectionLeft”的 UISwipeGestureRecognizer,但没有成功,因为即使我从屏幕中间开始向左上角滑动,处理程序也会被调用。
我是否需要对 UIGestureRecognizer 进行子类化,或者我可以使用 touchesBegan 和 touchesMoved 来处理这个问题?
最佳答案
无论如何,您都需要对其进行子类化才能使用 touchesBegan
和 touchesMoved
。我会做 UISwipeGestureRecognizerDirectionUp | UISwipeGestureRecognizerDirectionLeft
就像你说的,然后设置两个 CGRect
,一个用于可接受的起点,一个用于可接受的终点。然后使用 UIGestureRecognizerDelegate
方法 gestureRecognizer:shouldReceiveTouch:
,并使用 CGRectContainsPoint()
检查触摸点是否在可接受的起始矩形内。然后(我认为)在您的 UISwipeGestureRecognizer
子类中,覆盖 touchesEnded:withEvent:
,并检查结束触摸是否在可接受的矩形中。如果不是,请将状态设置为 UIGestureRecognizerStateCancelled
(或者您应该取消手势)。还要确保它附加到的 View 设置了 multipleTouchEnabled
属性。我实际上还没有尝试过这个,但是应该可以做到这一点。祝你好运!
编辑
实际上,如果您不想担心可接受的起点/终点的特定矩形值,并使其独立于设备,您可以这样做:
//swap in whatever percentage of the screen's width/height you want in place of ".75f"
//set the origin for acceptable start points
CGFloat startRect_x = self.view.frame.size.width * .75f;
CGFloat startRect_y = self.view.frame.size.height * .75f;
//set the size
CGFloat rectWidth = self.view.frame.size.width - startRect_x;
CGFloat rectHeight = self.view.frame.size.height - startRect_y;
//make the acceptable start point rect
CGRect startRect = CGRectMake(startRect_x, startRect_y, rectWidth, rectHeight);
//set the origin for the accepable end points
CGFloat endRect_x = self.view.center.x - rectWidth/2;
CGFloat endRect_y = self.view.center.y - rectHeight/2;
//make the acceptable end point rect
CGRect endRect = CGRectMake(endRect_x, endRect_y, rectWidth, rectHeight);
关于ios - 在 UIView 中检测对角滑动手势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11707257/