0

Is it possible in swift, passing a closure into selector?

for example, Is it possible to rewrite this code:

let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneAction(_:)))
    
@objc func doneAction(_ sender: UIBarButtonItem){
    self.myTextField?.resignFirstResponder()
}

to be:

let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: { _ sender in 
    self.myTextField?.resignFirstResponder()
})

I've tried the above code and got:

Cannot convert value of type '() -> ()' to expected argument type 'Selector'
Ahmad Abdullah
  • 1,645
  • 1
  • 16
  • 25

1 Answers1

1

It's not possible. If the parameter type is a selector, you must pass in a selector. Some classes offer both options, using different methods, but UIBarButtonItem is not one of them.

rodskagg
  • 3,827
  • 4
  • 27
  • 46