若直接判斷tapCount的次數(shù)調(diào)用相應的方法,那么為出現(xiàn)奇怪的現(xiàn)象,雙擊的時候會先調(diào)用單擊方法,再調(diào)用雙擊方法,那么我們?nèi)绾谓鉀Q該問題呢?
** 解決方法:
1.若tapCount==1 延遲調(diào)用單擊方法(為了判斷是否實單雙擊的處理)**
if (count == 1) {
[self performSelector:@selector(sigleTapAction) withObject:nil afterDelay:0.3];
}```
**2.若tapCount==2,先取消單擊方法的調(diào)用,再調(diào)用雙擊方法**
if (count == 2) {
//取消單擊
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sigleTapAction) object:nil];
[self doubleTapAction];
}
*代碼如下:*
import "ViewController.h"
import "MyView.h"
@interface ViewController ()
@end
@implementation ViewController
-
(void)viewDidLoad {
[super viewDidLoad];MyView *view = [[MyView alloc] initWithFrame:CGRectMake(50, 200, 200, 200)];
view.backgroundColor = [UIColor orangeColor];
[self.view addSubview:view];
}
@end
import "MyView.h"
@implementation MyView
-
(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {}
return self;
} (void) sigleTapAction{
NSLog(@"單擊");
}-
(void) doubleTapAction {
NSLog(@"雙擊");
}
//當一個或多個手指觸碰到屏幕時 -
(void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
NSInteger count = [touch tapCount];
//問題:當你雙擊的時候,會調(diào)用單擊的方法.//重點:雙擊事件取消單擊
if (count == 1) {
[self performSelector:@selector(sigleTapAction) withObject:nil afterDelay:0.3];
}
if (count == 2) {
//取消單擊
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sigleTapAction) object:nil];
[self doubleTapAction];
}
}
@end```