系統自帶的 UILongPressGestureRecognizer 只能判斷「按了多久」,無法滿足更細緻的交互需求。當你需要自定義一套長按判定邏輯時,正確做法是繼承 UIGestureRecognizer 自己實現一個手勢類。本文用一個 Demo 走完整流程。
新建一個類,命名為 LongPressGestureRecognizer,父類選擇 UIGestureRecognizer。
LongPressGestureRecognizer.h:
#import <UIKit/UIKit.h> @interface LongPressGestureRecognizer : UIGestureRecognizer @end
LongPressGestureRecognizer.m:
#import "LongPressGestureRecognizer.h"
#import <UIKit/UIGestureRecognizerSubclass.h>
NSInteger timer1;
NSInteger timer2;
@implementation LongPressGestureRecognizer
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
NSDate *nowDate = [NSDate date];
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:@"ss"];
timer1 = [[dateformatter stringFromDate:nowDate] integerValue];
[dateformatter release];
NSLog(@"%d", timer1);
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesEnded:touches withEvent:event];
NSDate *nowDate = [NSDate date];
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:@"ss"];
timer2 = [[dateformatter stringFromDate:nowDate] integerValue];
[dateformatter release];
NSLog(@"%d", timer2);
if ((timer2 - timer1) >= 2) {
self.state = UIGestureRecognizerStateEnded;
}
}
@end
這裡有幾個要點。首先,#import <UIKit/UIGestureRecognizerSubclass.h> 是必須的——只有引入這個私有頭文件,子類才被允許直接給 state 賦值,這也是自定義手勢能生效的關鍵。其次,重寫 touches 系列方法時一定要調用 super 的實現,否則手勢狀態機不完整。最後,判定邏輯是記錄按下與抬起的時間差,超過 2 秒才把狀態置為 UIGestureRecognizerStateEnded,未達標則手勢不會被識別。
(註:示例中用秒級格式化字符串做計時,精度較粗且存在跨分鐘邊界問題。實戰中更穩妥的做法是用 CACurrentMediaTime() 或 [NSDate timeIntervalSinceReferenceDate] 記錄浮點時間戳做差值判斷。)
ViewController.h:
#import <UIKit/UIKit.h> @interface DXWViewController : UIViewController <UIGestureRecognizerDelegate> @end
ViewController.m:
#import "DXWViewController.h"
#import "LongPressGestureRecognizer.h"
@interface DXWViewController ()
@end
@implementation DXWViewController
- (void)viewDidLoad
{
[super viewDidLoad];
LongPressGestureRecognizer *longPress =
[[LongPressGestureRecognizer alloc] initWithTarget:self action:@selector(LongPress:)];
[self.view addGestureRecognizer:longPress];
}
-(void)LongPress:(LongPressGestureRecognizer *)my
{
NSLog(@"OK");
}
@end
自定義手勢類裡的 touchesBegan:withEvent: 和視圖控制器裡的 touchesBegan:withEvent: 有本質不同:
· ViewController 中的 touchesBegan 是針對整個 view 而言的,只要在其管轄範圍內的觸摸都會走到這裡。
· 自定義手勢中的 touchesBegan 屬於手勢識別器,手勢必須先通過 addGestureRecognizer: 綁定到某個特定的 view 上,只有作用於該 view 的觸摸才會被跟蹤,並最終觸發綁定的 action。
理解這一層區分很重要:手勢識別器走的是 UIKit 的分層觸摸分發體系,它會先於普通的 touches 回調參與事件響應鏈的判定。當自定義手勢與系統手勢衝突時,可以通過實現 gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer: 來控制共存關係。