小编典典

点击按钮并长按手势

swift

我的手势有点麻烦。

我正在尝试在同一个按钮上同时使用水龙头和长按,所以我已经使用了

@IBAction func xxx (sender: UITapGestureRecognizer)

@IBAction func xxx (sender: UILongPressGestureRecognizer)

但是当我点击时,我的按钮似乎对这两种功能都有反应。可能是什么问题?

func long(longpress: UIGestureRecognizer){
    if(longpress.state == UIGestureRecognizerState.Ended){
    homeScoreBool = !homeScoreBool
    }else if(longpress.state == UIGestureRecognizerState.Began){
        print("began")
    }
}

阅读 316

收藏
2020-07-07

共1个答案

小编典典

很难说什么与您的代码不兼容,仅提供了两行,但是我建议您以这种方式进行:

为按钮创建插座

@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 5.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
    }
}
2020-07-07