I want to dismiss keyboard when click on done button of UIBarButtonItem and I Don't want to add selector function @objc method.
#selector(UIView.endEditing) - This selector is working fine with UITapGestureRecognizer
let tapGesture = UITapGestureRecognizer(target: view, action:#selector(UIView.endEditing))
view.addGestureRecognizer(tapGesture)
Doing same thing with UIBarButtonItem - It Crashing
let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(UIView.endEditing))
I am adding this done button to ToolBar adding reference code here
let toolBar = UIToolbar()
toolBar.sizeToFit()
let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(UIView.endEditing))
let spacebar = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
toolBar.setItems([spacebar ,done], animated: false)
firstnameField.inputAccessoryView = toolBar
All things are working fine but when I tap on Done button it will crash.
CodePudding user response:
Thats because you are setting the target to self
in the UIBarButtonItem
scenario.
It should not be self
because your class is not handling this event and that's why it crashes.
Make the target the view like you did in the gesture:
let done = UIBarButtonItem(barButtonSystemItem: .done,
target: view, // Not self
action: #selector(UIView.endEditing))
I think this should solve it