Ad
Selector UIView.endEditing Crashing With UIBarButtonItem But It's Working With UITapGestureRecognizer Swift 5
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.
Ad
Answer
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
Ad
source: stackoverflow.com
Related Questions
- → How to write this recursive function in Swift?
- → Send email from a separated file using Swift Mailer
- → Laravel Mail Queue: change transport on fly
- → "TypeError: undefined is not an object" when calling JS function from Swift in tvOS app
- → Are Global/Nested functions in JavaScript implemented as closures?
- → JavascriptCore: executing a javascript-defined callback function from native code
- → Swift SHA1 function without HMAC
- → Shopify GraphQL using swift not getting response
- → How to disconnect git for a project in intellij?
- → Sending a request to a php web service from iOS
- → Add only objects that don't currently exist to Realm database
- → How to sort using Realm?
- → Realm object as member is nil after saving
Ad