将函数参数传递给 Swift 中的选择器
Pass function argument into selector in Swift
我总共有五个拾取器。我想为他们每个人创建一个完成按钮。我想为每个选择器使用不同的选择器来执行不同的操作。为了设置完成按钮,我试图对所有按钮使用相同的方法,但我不知道如何将函数参数传递给 Swift.
中的选择器
func createDoneButton(txtField: UITextField, donePressed: /* What do I need here? */) {
let toolbar = UIToolbar() // create toolbar
toolbar.sizeToFit() // toolbar fits the size of the screen
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed)) // action when the done button was pressed
toolbar.setItems([doneBtn], animated: true)
txtField.inputAccessoryView = toolbar
}
您可以在问题中找到答案:)
只需使用 Selector
参数类型,不需要 #selector()
func createDoneButton(txtField: UITextField, donePressed: Selector){
let toolbar = UIToolbar() // create toolbar
toolbar.sizeToFit() // toolbar fits the size of the screen
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: donePressed) // action when the done button was pressed
toolbar.setItems([doneBtn], animated: true)
txtField.inputAccessoryView = toolbar
}
我总共有五个拾取器。我想为他们每个人创建一个完成按钮。我想为每个选择器使用不同的选择器来执行不同的操作。为了设置完成按钮,我试图对所有按钮使用相同的方法,但我不知道如何将函数参数传递给 Swift.
中的选择器func createDoneButton(txtField: UITextField, donePressed: /* What do I need here? */) {
let toolbar = UIToolbar() // create toolbar
toolbar.sizeToFit() // toolbar fits the size of the screen
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed)) // action when the done button was pressed
toolbar.setItems([doneBtn], animated: true)
txtField.inputAccessoryView = toolbar
}
您可以在问题中找到答案:)
只需使用 Selector
参数类型,不需要 #selector()
func createDoneButton(txtField: UITextField, donePressed: Selector){
let toolbar = UIToolbar() // create toolbar
toolbar.sizeToFit() // toolbar fits the size of the screen
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: donePressed) // action when the done button was pressed
toolbar.setItems([doneBtn], animated: true)
txtField.inputAccessoryView = toolbar
}