为了账号安全,请及时绑定邮箱和手机立即绑定

UIButton长按事件

UIButton长按事件

iOS
函数式编程 2019-12-20 10:07:30
我想模仿长按按钮,该怎么办?我认为需要一个计时器。我知道了,UILongPressGestureRecognizer但是我该如何利用这种类型呢?
查看完整描述

3 回答

?
森栏

TA贡献1810条经验 获得超5个赞

您可以通过创建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");

    }

}

现在,这将是基本方法。您还可以设置印刷机的最短持续时间以及允许的错误数量。还要注意的是,如果您在识别出手势之后会多次调用该方法,那么如果您想在其结束时执行某些操作,则必须检查其状态并进行处理。


查看完整回答
反对 回复 2019-12-20
?
富国沪深

TA贡献1790条经验 获得超9个赞

作为可接受答案的替代方法,可以使用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,您会在系统抓住长按后立即看到长按的效果,甚至在将手指从屏幕上抬起之前也是如此。


查看完整回答
反对 回复 2019-12-20
?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

接受答案的Swift版本

我对using进行了其他修改,UIGestureRecognizerState.Began而不是.Ended因为这可能是大多数用户自然希望的。尝试一下它们,然后自己看看。


import UIKit


class 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")

    }

}


查看完整回答
反对 回复 2019-12-20
  • 3 回答
  • 0 关注
  • 1014 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信