当前位置:  开发笔记 > IOS > 正文

按钮水龙头和长按手势

如何解决《按钮水龙头和长按手势》经验,为你挑选了1个好方法。



1> Rashwan L..:

很难说没有使用你的代码,你只提供了两行,但我建议你这样做:

改为为按钮创建一个插座

@IBOutlet weak var myBtn: UIButton!

并在您viewDidLoad()添加手势按钮

let tapGesture = UITapGestureRecognizer(target: self, action: "normalTap")  
let longGesture = UILongPressGestureRecognizer(target: self, action: "longTap:")
tapGesture.numberOfTapsRequired = 1
myBtn.addGestureRecognizer(tapGesture)
myBtn.addGestureRecognizer(longGesture)

然后创建处理水龙头的动作

func normalTap(){

    print("Normal tap")
}

func longTap(sender : UIGestureRecognizer){
    print("Long tap")
    if sender.state == .Ended {
    print("UIGestureRecognizerStateEnded")
    //Do Whatever You want on End of Gesture
    }
    else if sender.state == .Began {
        print("UIGestureRecognizerStateBegan.")
        //Do Whatever You want on Began of Gesture
    }
}

Swift 3.0版本:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.normalTap))
let longGesture = UILongPressGestureRecognizer(target: self, action: Selector(("longTap:")))
tapGesture.numberOfTapsRequired = 1
myBtn.addGestureRecognizer(tapGesture)
myBtn.addGestureRecognizer(longGesture)

func normalTap(){

    print("Normal tap")
}

func longTap(sender : UIGestureRecognizer){
    print("Long tap")
    if sender.state == .ended {
        print("UIGestureRecognizerStateEnded")
        //Do Whatever You want on End of Gesture
    }
    else if sender.state == .began {
        print("UIGestureRecognizerStateBegan.")
        //Do Whatever You want on Began of Gesture
    }
}

更新了Swift 4.x的语法:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(normalTap))
button.addGestureRecognizer(tapGesture)

let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap))
button.addGestureRecognizer(longGesture)

@objc func normalTap(_ sender: UIGestureRecognizer){
    print("Normal tap")
}

@objc func longTap(_ sender: UIGestureRecognizer){
    print("Long tap")
    if sender.state == .ended {
        print("UIGestureRecognizerStateEnded")
        //Do Whatever You want on End of Gesture
    }
    else if sender.state == .began {
        print("UIGestureRecognizerStateBegan.")
        //Do Whatever You want on Began of Gesture
    }
}


@AlvinWan,对于迟到的回复感到抱歉,但这是因为`UILongPressGestureRecognizer`有两个状态,开始和结束.我用一个例子更新了代码.请注意,我在longTap中添加了一个参数,并在`longGesture``UILongPressGestureRecognizer`中添加了一个":".
推荐阅读
跟我搞对象吧
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有