如何在多次按下时触发按钮操作?

时间:2017-07-21 10:17:35

标签: ios swift3

我是Swift 3的新手。目前,我有一个UIBarButtonItem。如何只在按下多次按钮时触发此按钮操作?例如,只有当用户按下此按钮两次时才会显示ViewController。

3 个答案:

答案 0 :(得分:1)

UIBarButtonItem创建自定义视图并为自定义视图添加UITapGestureRecognizer,并将numberOfTapsRequired属性值设置为2

示例代码:

 class viewController: UIViewController {

        var doubleTapGesture: UITapGestureRecognizer!
        var barButton: UIBarButtonItem!
        var button: UIButton!

        override func viewDidLoad() {
            super.viewDidLoad()

            button = UIButton(type: .custom)
            button.setTitle("title", for: .normal)
            button.frame = CGRect(x: 0, y: 0, width: 64, height: 30)

            doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(viewController.buttonClicked))
            doubleTapGesture.numberOfTapsRequired = 2

            button.addGestureRecognizer(doubleTapGesture)

            barButton = UIBarButtonItem(customView: button);
            navigationItem.rightBarButtonItem = barButton
        }

        func buttonClicked() {
            // Method for UITapGestureRecognizer
        }
    }

答案 1 :(得分:1)

使用UIButton代替UIBarButtonItem并定义其" Touch Down Repeat"事件而不是" Touch Up Inside"。 双击按钮时触摸向下重复触发。

检查下图以供参考

enter image description here

答案 2 :(得分:0)

添加      UITapGestureRecognizer到您的UIBarButtonItem,如下所示。

func addBarButton() -> UIBarButtonItem
{
        let btnImage    = UIImage(named: "imageName")!
        let imageButton : UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
        imageButton.setBackgroundImage(btnImage, for: UIControlState())

        let doubleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.buttonAction(_:)))
        doubleTap.numberOfTapsRequired = 2
        imageButton.addGestureRecognizer(doubleTap)

        return UIBarButtonItem(customView: imageButton)
}

从viewDidLoad函数调用bellow行。

navigationItem.rightBarButtonItems  = [addBarButton()]