2015-12-31 174 views
14

我對手勢有點麻煩。按鈕水龍頭和長按手勢

我試圖在同一按鈕上使用踢踏舞及長按,所以我用

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

回答

39

很難說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 
    } 
} 
+0

謝謝它完美的工作,但當我嘗試兩次使用長時間按下它的行動兩次,你知道爲什麼嗎?謝謝先生 –

+0

也許它是捕獲雙擊? – Marcelo

+2

@AlvinWan,對於遲到的回覆感到抱歉,但是這是因爲UILongPressGestureRecognizer有兩個狀態,開始和結束。我用一個例子更新了代碼。請注意,我已經爲longTap添加了一個參數,並向'longGesture'' UILongPressGestureRecognizer'添加了一個「:」。 –