很難說what's不是你的代碼的工作,與您所提供的只有兩行,但我會建議你做它用這種方式來代替:
創建一個出口您的按鈕,而不是
@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
}
}
雨燕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
}
}
爲雨燕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
}
}
謝謝它完美的工作,但當我嘗試兩次使用長時間按下它的行動兩次,你知道爲什麼嗎?謝謝先生 –
也許它是捕獲雙擊? – Marcelo
@AlvinWan,對於遲到的回覆感到抱歉,但是這是因爲UILongPressGestureRecognizer有兩個狀態,開始和結束。我用一個例子更新了代碼。請注意,我已經爲longTap添加了一個參數,並向'longGesture'' UILongPressGestureRecognizer'添加了一個「:」。 –