UIButton长按事件

我想模仿长按按钮,该怎么办?我认为需要一个计时器。我知道了,UILongPressGestureRecognizer但是我该如何利用这种类型呢?



函数式编程
浏览 1024回答 3
3回答

森栏

您可以通过创建UILongPressGestureRecognizer实例并将其附加到按钮开始。UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];[self.button addGestureRecognizer:longPress];[longPress release];然后实现处理手势的方法- (void)longPress:(UILongPressGestureRecognizer*)gesture {    if ( gesture.state == UIGestureRecognizerStateEnded ) {         NSLog(@"Long Press");    }}现在,这将是基本方法。您还可以设置印刷机的最短持续时间以及允许的错误数量。还要注意的是,如果您在识别出手势之后会多次调用该方法,那么如果您想在其结束时执行某些操作,则必须检查其状态并进行处理。

富国沪深

作为可接受答案的替代方法,可以使用Interface Builder在Xcode中非常轻松地完成此操作。只需将“ 长按手势识别器”从对象库中拖放到想要长按动作的按钮顶部即可。接下来,将刚添加的“ 长按手势识别器 ”中的“动作”连接到视图控制器,选择类型为“发件人”的发件人UILongPressGestureRecognizer。在IBAction使用该代码的代码中,该代码与已接受答案中建议的代码非常相似:在Objective-C中:if ( sender.state == UIGestureRecognizerStateEnded ) {     // Do your stuff here}或在Swift中:if sender.state == .Ended {    // Do your stuff here}但我必须承认,尝试后,我更喜欢@shengbinmeng提出的建议,以作为已接受答案的注释,该建议使用:在Objective-C中:if ( sender.state == UIGestureRecognizerStateBegan ) {     // Do your stuff here}或在Swift中:if sender.state == .Began {    // Do your stuff here}区别在于,使用Ended,您可以在抬起手指时看到长按的效果。使用Began,您会在系统抓住长按后立即看到长按的效果,甚至在将手指从屏幕上抬起之前也是如此。

哈士奇WWW

接受答案的Swift版本我对using进行了其他修改,UIGestureRecognizerState.Began而不是.Ended因为这可能是大多数用户自然希望的。尝试一下它们,然后自己看看。import UIKitclass ViewController: UIViewController {    @IBOutlet weak var button: UIButton!    override func viewDidLoad() {        super.viewDidLoad()        // add gesture recognizer        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))        self.button.addGestureRecognizer(longPress)    }    func longPress(gesture: UILongPressGestureRecognizer) {        if gesture.state == UIGestureRecognizerState.began {            print("Long Press")        }    }    @IBAction func normalButtonTap(sender: UIButton) {        print("Button tapped")    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

iOS