选择器 UIView.endEditing 与 UIBarButtonItem 一起崩溃,但它与 UITapGestureRecognizer 一起工作 Swift 5
Selector UIView.endEditing crashing with UIBarButtonItem but it's working with UITapGestureRecognizer Swift 5
我想在单击 UIBarButtonItem 的完成按钮时关闭键盘,我不想添加选择器函数@objc 方法。
#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))
我正在将此完成按钮添加到工具栏,在此处添加参考代码
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
崩溃图像:
一切正常,但当我点击“完成”按钮时,它会崩溃。
那是因为您在 UIBarButtonItem
场景中将目标设置为 self
。
它不应该是 self
因为你的 class 没有处理这个事件,这就是它崩溃的原因。
像在手势中那样将目标设为视图:
let done = UIBarButtonItem(barButtonSystemItem: .done,
target: view, // Not self
action: #selector(UIView.endEditing))
我认为这应该可以解决问题
我想在单击 UIBarButtonItem 的完成按钮时关闭键盘,我不想添加选择器函数@objc 方法。
#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))
我正在将此完成按钮添加到工具栏,在此处添加参考代码
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
崩溃图像:
一切正常,但当我点击“完成”按钮时,它会崩溃。
那是因为您在 UIBarButtonItem
场景中将目标设置为 self
。
它不应该是 self
因为你的 class 没有处理这个事件,这就是它崩溃的原因。
像在手势中那样将目标设为视图:
let done = UIBarButtonItem(barButtonSystemItem: .done,
target: view, // Not self
action: #selector(UIView.endEditing))
我认为这应该可以解决问题