与 类似UIButton
,可以通过 的tag
属性传递参数UIBarButtonItem
。
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