首页 > 解决方案 > 键盘不会随着 resignFirstResponder 消失

问题描述

我有一个视图控制器,需要用户选择几件事。直接使用 UIPickerView 是行不通的,因为它们占用了太多空间。所以我有几个 UITextField,当用户选择一个时,它会弹出一个模式视图控制器。到目前为止它工作正常,除非已经有一个可见的键盘。发生这种情况时,会显示模态视图控制器,但它会被之前的键盘覆盖。这个键盘似乎没有连接到任何 UITextField,因为按下它的键不会导致字符出现在任何 UITextField 中。尽管文本字段中确实出现了闪烁的光标。

protocol ModalPickerTarget {
    var cancelCallback: (() -> Void)? { set get }
    var selectCallback: ((String) -> Void)? { set get }
}

class ModalPicker<T> where T: UIViewController, T: ModalPickerTarget {
    weak var controller: UIViewController!
    weak var textField: UITextField!

    init(textField: UITextField, controller: UIViewController) {
        self.controller = controller
        self.textField = textField
        textField.addTarget(self, action: #selector(ModalPicker.show), for: .editingDidBegin)
    }

    @objc func show(sender: AnyObject) {
        var modal = T()

        print("First responder: \(self.textField.isFirstResponder)")
        self.textField.resignFirstResponder()
        modal.modalPresentationStyle = .overCurrentContext
        modal.modalTransitionStyle = .crossDissolve

        modal.cancelCallback = {
            modal.dismiss(animated: true, completion: nil)
        }

        modal.selectCallback = {
            modal.dismiss(animated: true, completion: nil)
            self.textField.text = $0
        }

        self.controller.present(modal, animated: true, completion: nil)
    }
}

print 语句表明这textField是第一响应者。我也尝试过调用endEditing父视图和模态视图但没有任何效果。

这是一些屏幕截图

模态显示正确 键盘不隐藏

标签: iosswiftuiviewcontrollerresignfirstresponder

解决方案


你必须返回 falsetextFieldShouldBeginEditing

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    // Implement your Picker there
  return false
}

推荐阅读