iOS - 双击 uibutton [英] iOS - Double tap on uibutton
问题描述
我有一个按钮,我正在测试它的点击,点击它改变背景颜色,点击两次另一种颜色,再次点击三下另一种颜色.代码是:
I have a button and I'm testing the taps on it, with one tap it change a background color, with two taps another color and with three taps another color again. The code is:
- (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];
}
问题是第一个水龙头不起作用,另一个是.如果我在没有按钮的情况下使用此代码,它可以完美运行.谢谢.
The problem is that the first tap don't works, the other yes. If I use this code without button it works perfectly. Thanks.
推荐答案
如果你想在点击按钮时改变颜色,你应该在 viewDidLoad
方法中在按钮上添加这些手势,而不是在相同的按钮操作上.上面的代码将在点击按钮时重复添加手势到 self.view
而不是在 button
上.
If you want the colors to change on tap of button, you should add these gestures on button in viewDidLoad
method or so rather than on the same button action. The above code will repeatedly add gestures on tap of the button to the self.view
and not on 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];
}
这篇关于iOS - 双击 uibutton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!