2012年7月18日 星期三

Hold Button Event

這次來分享在ios上如何偵測長壓按鈕的訊息

因為ios本身storyboard沒有提供這個函式
所以用以下的程式碼來宣告一個UILongPressGestureRecognizer
用它來掌控時間到了要呼喚哪個函式
範例中是0.3秒
UILongPressGestureRecognizer * recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];    
        recognizer.minimumPressDuration = 0.3f;  
        [downButton addGestureRecognizer:recognizer];
        [recognizer release];

常見的問題是 會在select時呼叫自己宣告長壓時的函式
但那是錯誤的
要再判斷長壓的狀態才去執行該做的事情
所以以handleLongPress這個函式來判斷
- (void)handleLongPress:(UILongPressGestureRecognizer*)sender
{ 
    if (sender.state == UIGestureRecognizerStateEnded)
    {
  //      NSLog(@"Long press Ended");
    }
    else
    {
        [self moveFastDown];
    }
}

UIGestureRecognizerStateEnded時不作事情
這是當長壓後放開按鈕時會觸發的狀態
所以最常看到的問題就是長壓後會觸發兩次
就是因為要正確的分辨狀態再執行
以上

沒有留言:

張貼留言