iOS - 双击uibutton

18

我有一个按钮,我正在测试它的点击功能。一次点击会改变背景颜色,两次点击会改变另一个颜色,三次点击会再次改变颜色。

代码如下:

- (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中添加呢? - iDev
因为我必须仅在视图的一小部分上使用此手势。 - Kerberos
但是你的代码将手势设置在整个“self.view”上。 你应该按照我的回答进行更改。 - iDev
1个回答

20

如果你希望在按下按钮时改变颜色,应该在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];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接