我有一个按钮,正在测试其上的水龙头,一个水龙头会改变背景色,两个水龙头会改变另一种颜色,而三个水龙头又会改变另一种颜色。
代码是:

- (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];
}

问题是第一次点击不起作用,而另一个则可以。
如果我不带按钮使用此代码,则效果很好。
谢谢。

最佳答案

如果要在单击按钮时更改颜色,则应在viewDidLoad方法中在按钮上添加这些手势,而不要在同一按钮 Action 上添加这些手势。上面的代码将在点击按钮时反复向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];
}

关于objective-c - iOS-双击uibutton,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13750014/

10-09 09:37