2012-12-06 36 views
14

我有一个按钮,我正在测试它的按键,只需轻轻一按,它就会更改背景颜色,两次轻击另一种颜色,再次使用三次轻拍另一种颜色。 的代码是: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]; } 

的问题是,第一抽头不工作,其他的肯定。 如果我使用这个代码没有按钮,它完美的作品。 谢谢。

+0

您是否在按钮水龙头上添加了这些手势?为什么不在viewDidLoad中添加它? – iDev

+0

因为我只能在视图的一小部分上使用此手势。 – Kerberos

+0

但是你的代码是在整个'self.view'上设置手势。你应该改变它,如我的答案中所示。 – iDev

回答

17

如果您希望按钮上的颜色发生变化,您应该在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]; 
}