按钮水龙头和长按手势

时间:2015-12-31 15:13:46

标签: ios swift uigesturerecognizer uitapgesturerecognizer

我的手势有点麻烦。

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

@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")
    }
}

1 个答案:

答案 0 :(得分:55)

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

为您的按钮创建一个插座

@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(_:)))
tapGesture.numberOfTapsRequired = 1
myBtn.addGestureRecognizer(tapGesture)

let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap(_:)))
myBtn.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
    }
}