2014-10-07 26 views
2

當某人在按鈕內滑動時,我想要執行一次操作。如何在swift中實現手勢識別器後找到按鈕標籤?

我當前的代碼如下:

let recogniser = UISwipeGestureRecognizer(target: self, action: "didTapButton2:") 
    recogniser.direction = .Up 
    button.addGestureRecognizer(recogniser) 

    func didTapButton2(sender: UIGestureRecognizer!) { 

    //Here I want to be able to recognise which button this was sent from (they are all tagged) 
    let button = sender. as UIButton //Gives an error 

我需要使用手勢識別器,而不是UIControlEvents,因爲我需要的情況下,只激活一次。使用這種方式會導致事件發生時間 - 只需要它去一次:

button.addTarget(self, action: "didTapButton2:", forControlEvents: .TouchDragInside) 

有沒有人有解決方案?謝謝

回答

6

A UIGestureRecognizer有一個名爲view的屬性,它是它所連接的視圖。視圖被聲明爲可選項,因此您需要打開它:

if let button = sender.view as? UIButton { 
    // use button 
    if button.tag == 10 { 
     // handle button tagged with 10 
    } 
}