简体   繁体   中英

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
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM