2012-12-06 60 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]; 
}