当我第一次点击swift中的按钮时,按钮单击不能与UITapGestureRecognizer一起使用

时间:2017-09-06 12:30:26

标签: ios swift uibutton

我在点击按钮时实现了UITapGestureRecognizer和UILongPressGestureRecognizer。我的问题是,当我第一次点击按钮时它不起作用,但第二次按下按钮时它开始工作。

let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap(_:)))
    longGesture.minimumPressDuration = 0.5
    button.addGestureRecognizer(longGesture)
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(normalTap(_:)))
    tapGesture.delegate = self
    tapGesture.numberOfTouchesRequired = 1
    tapGesture.numberOfTapsRequired = 1
    button.addGestureRecognizer(tapGesture) 
 @objc func longTap(_ sender: UIGestureRecognizer){
    print("long tap")

}
@objc func normalTap(_ sender: UIGestureRecognizer){

    print("Normal tap")
}

1 个答案:

答案 0 :(得分:0)

试试这个

class ViewController: UIViewController, UIGestureRecognizerDelegate {

@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
     super.viewDidLoad()
     // Do any additional setup after loading the view, typically from a nib.
     let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap(_:)))
     longGesture.minimumPressDuration = 0.5
     button.addGestureRecognizer(longGesture)
 }


 @IBAction func buttonClicked(_ sender: Any) {
     let tapGesture = UITapGestureRecognizer(target: self, action: #selector(normalTap(_:)))
     tapGesture.delegate = self
     tapGesture.numberOfTouchesRequired = 1
     tapGesture.numberOfTapsRequired = 1
     button.addGestureRecognizer(tapGesture)
 }

 @objc func longTap(_ sender: UIGestureRecognizer){
     print("long tap")
 }

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