IOS - Дважды нажмите на uibutton

У меня есть кнопка, и я тестирую краны на ней, одним нажатием на нее меняется цвет фона, с двумя кранами другого цвета и тремя кранами другого цвета. Код:

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

Проблема в том, что первый ответ не работает, другой - да. Если я использую этот код без кнопки, он отлично работает. Спасибо.

Ответы

Ответ 1

Если вы хотите, чтобы цвета менялись при нажатии кнопки, вы должны добавить эти жесты на кнопку в методе 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];
}