动作当我在iPhone中持有UIButton 2秒时触发

Sid*_*qui 14 iphone ios4 ios-simulator

我有一个UIButton在我的应用程序和一个动作,当我TouchDown触发UIButton.

是否有可能UIButton在iPhone 上检测到触摸并保持?我希望当用户按住按钮2秒钟或更长时间时触发我的动作.

有任何想法吗?

Emp*_*ack 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];
Run Code Online (Sandbox Code Playgroud)

为了让你的动作只被触发一次(即,当2秒持续时间结束时),确保你的doAction:方法看起来像这样,

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

    if (recognizer.state == UIGestureRecognizerStateBegan) {

        // Your code here
    }
}
Run Code Online (Sandbox Code Playgroud)