objective-c ios xcode button gesture

objective c - iOS-doble toque en uibutton



objective-c xcode (1)

Tengo un botón y estoy probando los toques, con un toque cambia un color de fondo, con dos toques otro color y con tres toques otro color de nuevo. El código es:

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

El problema es que el primer toque no funciona, el otro sí. Si utilizo este código sin botón funciona perfectamente. Gracias.


Si desea que los colores cambien con solo tocar un botón, debe agregar estos gestos en el botón en el método viewDidLoad en lugar de hacerlo en la misma acción del botón. El código anterior agregará repetidamente gestos con solo tocar el botón a la self.view y no al 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]; }