2016-04-23 48 views
0

所以當我長按一個按鈕,它認識到長按,但「測試」被調用兩次。我如何防止這種情況發生?UILongPressGesture被叫兩次

@IBOutlet weak var button2: UIButton! 

func longPressMe(){ 
    print("test") 
} 

func longPressGes(){ 
    let longpress = UILongPressGestureRecognizer(target: self, action: "longPressMe") 
    longpress.minimumPressDuration = 1 
    button2.addGestureRecognizer(longpress) 
} 


override func viewDidLoad() { 
    super.viewDidLoad() 
    longPressGes() 
} 

回答

-1

有一個嘗試,這裏是如何使用#selector:

func longPressMe(recognizer: UILongPressGestureRecognizer) { 
    // do stuff here 
} 

func longPressGes(){ 
    let longpress = UILongPressGestureRecognizer(target: self, action: #selector(yourViewController.longPressMe(_:))) 
    longpress.minimumPressDuration = 1 
    button2.addGestureRecognizer(longpress) 
} 
+0

「謝謝。我很感激。暫時得不到它。 –

+0

這個答案甚至沒有解決問題中所述的問題...... –

2

您必須檢查手勢識別器的狀態。更改longPressMe()到這樣的事情:

func longPressMe(recognizer: UILongPressGestureRecognizer) { 
    guard recognizer.state == .Began else { return } 

    // do stuff here 
} 
+0

與BOT我的方式和你的方式我不斷收到***終止應用程序由於未捕獲異常「NSInvalidArgumentException」,原因:' - [testtest.ViewController pressAction]:發送到實例的無法識別的選擇器 –

+0

您無法再使用字符串作爲選擇器。改用新的'#選擇器'語法。 –

+0

@DAMONGONZALEZ將選擇器更改爲'#selector(longPressMe(_ :))',或者如果它是舊版本的Xcode/Swift,請使用'action:「longPressMe:」' –