2016-09-08 105 views
0

我有一個UIToolbar項目的數組,它顯示inputField成爲第一響應者的時間。有沒有辦法在Swift中使用#selector調用參數功能

//... code 
toolBar.items = [ 
      UIBarButtonItem(title: "Button 1", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(myFunction))] 

myInputField.inputAccessoryView = toolBar 

是否有可能從上面的示例調用myFunction帶參數?

喜歡的東西...

... #selector(myFunction(someParameter))) 

回答

1

類似UIButton,參數可以通過的UIBarButtonItemtag屬性進行傳遞。

override func viewDidLoad() { 
    super.viewDidLoad() 

    let toolBar = UIToolbar() 
    let firstButton = UIBarButtonItem(title: "Button 1", style: UIBarButtonItemStyle.Done, target: self, action: #selector(myFunction)) 
    let secondButton = UIBarButtonItem(title: "Button 2", style: UIBarButtonItemStyle.Done, target: self, action: #selector(myFunction)) 
    firstButton.tag = 1 
    secondButton.tag = 2 
    toolBar.items = [ firstButton, secondButton ] 
    toolBar.sizeToFit() 
    textField.inputAccessoryView = toolBar 
} 

func myFunction(sender: UIBarButtonItem) { 
    print("Tapped: \(sender.tag)") 
} 

按一個按鈕就打印按鈕在這個例子中標籤:

Tapped: 1 // Tap button 1 
Tapped: 2 // Tap button 2 
+1

非常感謝你的幫助。 –

相關問題