web-dev-qa-db-ja.com

ボタンタップと長押しジェスチャー

ジェスチャーに少し問題があります。

同じボタンでタップと長押しの両方を使用しようとしているので、

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

あなたのコードで機能しないものを言うのは難しい、あなたが提供したのは2行だけですが、代わりにこの方法でそれを行うことをお勧めします:

代わりにボタンへのアウトレットを作成します

_@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
    }
}
_
56
Rashwan L