我有一个触摸操作,它是调整大小类场景的触发器,其中操作在触摸移动时开始,并且需要以touchesEnded结束。问题是,touchesEnd可能位于不同的UI视图上,因为用户正在拖动手指。如何注册* global“touchesEnded listener?
答案 0 :(得分:5)
您应该使用UIPanGestureRecognizer
。每次触发时,请检查手势识别器的state
。如果它是UIGestureRecognizerStateBegan
,则首先触摸视图,如果它是UIGestureRecognizerStateChanged
,那么用户正在移动他的手指,如果它是UIGestureRecognizerStateEnded
则用户已经抬起他的手指。
只要手势在您的视图上开始,即使在离开视图边界后,它也会继续(除非取消),因此您无需担心“使其全局化”。
使用以下命令初始化手势识别器:
UIPanGestureRecognizer *dragViewGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleDragView:)];
dragViewGestureRecognizer.maximumNumberOfTouches = 1;
[yourView addGestureRecognizer:dragViewGestureRecognizer];
然后使用您需要的代码填写以下方法:
- (void)handleDragView:(UIPanGestureRecognizer*)panGestureRecognizer {
switch (panGestureRecognizer.state) {
case UIGestureRecognizerStateBegan: {
//Code when dragging starts
break;
} case UIGestureRecognizerStateChanged: {
//Code while dragging is happening (if needed)
break;
} case UIGestureRecognizerStateEnded: {
//Code when dragging ends
break;
}
default:
break;
}
}