Search code examples
iosswiftparameter-passingselectoruitoolbar

Pass function argument into selector in Swift


I have five pickers in total. I want to create a done button for each one of them. I want to use a different selector for each one to to do different actions. To set up the done buttons I was trying to use the same method for all of them, but I do not know how to pass a function argument into the selector in 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
}

Solution

  • You can find the answer in your question :) Simply use Selector parameter type, and no need #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
    }