有没有办法在Swift中使用#selector调用带参数的函数

时间:2016-09-08 22:04:18

标签: swift function selector inputaccessoryview

我有一组UIToolbar个项目,显示inputField何时成为第一响应者。

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

myInputField.inputAccessoryView = toolBar

是否可以使用参数?

从上面的示例中调用myFunction

像...一样的东西。

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

1 个答案:

答案 0 :(得分:1)

UIButton类似,参数可以通过tag的{​​{1}}属性传递。

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