我有一个按钮,我正在测试它上面的水龙头,只需轻按一下它就可以改变背景颜色,两次点击另一种颜色,再用三次点击另一种颜色。 代码是:
- (IBAction) button
{
UITapGestureRecognizer *tapOnce = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnce:)];
UITapGestureRecognizer *tapTwice = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTwice:)];
UITapGestureRecognizer *tapTrice = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTrice:)];
tapOnce.numberOfTapsRequired = 1;
tapTwice.numberOfTapsRequired = 2;
tapTrice.numberOfTapsRequired = 3;
//stops tapOnce from overriding tapTwice
[tapOnce requireGestureRecognizerToFail:tapTwice];
[tapTwice requireGestureRecognizerToFail:tapTrice];
//then need to add the gesture recogniser to a view - this will be the view that recognises the gesture
[self.view addGestureRecognizer:tapOnce];
[self.view addGestureRecognizer:tapTwice];
[self.view addGestureRecognizer:tapTrice];
}
- (void)tapOnce:(UIGestureRecognizer *)gesture
{
self.view.backgroundColor = [UIColor redColor];
}
- (void)tapTwice:(UIGestureRecognizer *)gesture
{
self.view.backgroundColor = [UIColor blackColor];
}
- (void)tapTrice:(UIGestureRecognizer *)gesture
{
self.view.backgroundColor = [UIColor yellowColor];
}
问题是第一次点击不起作用,另一种是。 如果我使用没有按钮的代码,它可以很好地工作。 感谢。
答案 0 :(得分:18)
如果您希望点按按钮时更改颜色,则应使用viewDidLoad
方法左右按钮添加这些手势,而不是按相同的按钮操作。上面的代码会重复添加按钮的手势到self.view
,而不是button
。
- (void)viewDidLoad {
[super viewDidLoad];
UITapGestureRecognizer *tapOnce = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnce:)];
UITapGestureRecognizer *tapTwice = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTwice:)];
UITapGestureRecognizer *tapTrice = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTrice:)];
tapOnce.numberOfTapsRequired = 1;
tapTwice.numberOfTapsRequired = 2;
tapTrice.numberOfTapsRequired = 3;
//stops tapOnce from overriding tapTwice
[tapOnce requireGestureRecognizerToFail:tapTwice];
[tapTwice requireGestureRecognizerToFail:tapTrice];
//then need to add the gesture recogniser to a view - this will be the view that recognises the gesture
[self.button addGestureRecognizer:tapOnce]; //remove the other button action which calls method `button`
[self.button addGestureRecognizer:tapTwice];
[self.button addGestureRecognizer:tapTrice];
}