如果其他人需要它,这里是适合我的代码。目标是获得对长按和平移敏感的视图,包括长按之前没有平移的视图,反之亦然。
// setup
@property (strong,nonatomic) NSTimer *timer; // triggers the long press during pan
@property (strong,nonatomic) UIView *longPressView; // need this to track long press state
// view is the view we're interested in panning and long pressing
UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGR:)];
[view addGestureRecognizer:panGR];
// this starts a long press when no pan has occurred
UILongPressGestureRecognizer *longGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGR:)];
[view addGestureRecognizer:longGR];
当平底锅开始或发生变化时,启动计时器。如果计时器在平移结束之前到期(触摸释放),那么我们可以长按。
- (void)panGR:(UIPanGestureRecognizer *)gr {
if (gr.state == UIGestureRecognizerStateBegan) {
[self startTimer:gr.view];
} else if (gr.state == UIGestureRecognizerStateChanged) {
[self startTimer:gr.view];
// do whatever you want to do with pan state in this method
// in my case, I'm translating the view here
} else if (gr.state == UIGestureRecognizerStateEnded) {
if (self.longPressView) {
[self longPressEnded];
} else {
[self.timer invalidate];
}
}
}
我们为计时器提供视图的用户信息。您可能需要存储手势状态的其他部分,例如位置等。使用用户信息字典以相同的方式进行操作。
- (void)startTimer:(UIView *)view {
if (self.longPressView) return;
[self.timer invalidate];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self
selector:@selector(longPressTimer:)
userInfo:@{ @"view": view} repeats:NO];
}
-(void)longPressTimer:(NSTimer *)timer {
self.longPressView = timer.userInfo[@"view"];
[self longPressBegan];
}
由于计时器方法没有关联的 gr,因此请分解出我们通常放入 gr 处理程序中的所有逻辑,以便计时器处理程序和 gr 处理程序都可以调用它。
- (void)longPressGR:(UILongPressGestureRecognizer *)gr {
if (gr.state == UIGestureRecognizerStateBegan) {
self.longPressView = gr.view;
[self longPressBegan];
} else if (gr.state == UIGestureRecognizerStateEnded) {
[self longPressEnded];
}
}
- (void)longPressBegan {
NSLog(@"long press began");
}
- (void)longPressEnded {
self.longPressView = nil;
NSLog(@"long press ended");
}