2011-01-27 12 views
14

私のアプリケーションにUIButtonがあり、TouchDownのときに起動するアクションUIButtonアクションiPhoneでUIButtonを2秒間押したときにトリガする

iPhoneのUIButtonのTouch-and-Holdを検出することはできますか?ユーザーがボタンを2秒以上保持しているときに、自分のアクションがトリガーされるようにしたい。

すべてのアイデア?

答えて

27

UILongPressGestureRecognizerが必要です。例えば、

UILongPressGestureRecognizer *longPress_gr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(doAction:)]; 
[longPress_gr setMinimumPressDuration:2]; // triggers the action after 2 seconds of press 
[yourButton addGestureRecognizer:longPress_gr]; 

- (void)doAction:(UILongPressGestureRecognizer *)recognizer { 

    if (recognizer.state == UIGestureRecognizerStateBegan) { 

     // Your code here 
    } 
} 
+1

私はあなたのコードを試してみました。しかし、私の行動が2回トリガーするという問題が1つあります。 2秒後の最初のアクショントリガとタッチが終了したときの2回目。 – Siddiqui

+0

@アーマン:ああ..私は私の答えを編集しました。私はそれがうまくいくと思います。見てみな。 – EmptyStack

+1

ありがとうサイモン。本当に私にとって有益です。 – Siddiqui

2

、あなたのdoAction:方法は次のようになります持っていることを確認し、あなたの行動は(すなわち、2秒の期間が終わった時に)一度だけトリガー取得できるようにあなたはthis NBTouchAndHoldButtonを使うことができます。これはまさにあなたが望むものであり、それを実装するのは非常に簡単です:

TouchAndHoldButton * pageDownButton = [TouchAndHoldButton buttonWithType:UIButtonTypeCustom]; 
[pageDownButton addTarget:self action:@selector(pageDownAction:) forTouchAndHoldControlEventWithTimeInterval:0.2]; 

幸運!

関連する問題