如果 UITextField 是子视图,则不调用 becomeFirstResponder

becomeFirstResponder not called if UITextField is a subview

我遇到了一个关于 UITextField 的奇怪问题:

class AnnotateTextField: UIView {

    // MARK: - Views

    let textField = UITextField()

    // MARK: - Initializers

    init() {
        super.init(frame: .zero)

        setupViews()
    }

    @available(*, unavailable)
    private override init(frame: CGRect) {
        fatalError("init(frame:) has not been implemented")
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - Setup

    private func setupViews() {
        let textField = UITextField()
        textField.font = UIFont.systemFont(ofSize: 100.0)
        textField.textColor = .white

        backgroundColor = .black.withAlphaComponent(0.7)
        clipsToBounds = true
        layer.cornerRadius = 16.0
        // Paint stays behind it
        layer.zPosition = 1

        addSubview(textField)
        textField.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(16.0)
        }
    }

}

如果我将其添加到我的视图并调用 becomesFirstResponder,键盘将不会显示:

private func addText() {
    let annotateTextField = AnnotateTextField()

    addSubview(annotateTextField)
    annotateTextField.snp.makeConstraints { make in
        make.center.equalToSuperview()
    }

    annotateTextField.textField.becomeFirstResponder()
}

但是对于常规 UITextField 它工作正常:

private func addText() {
    let text = UITextField()
    addSubview(text)
    // This shows the keyboard
    text.becomeFirstResponder()
}

我在这里做错了什么?我尝试在 AnnotateTextField 上设置启用用户交互,但没有任何区别。

我认为问题出在 setupViews 函数中。您正在该函数中创建一个新的文本字段对象,并在此文本字段上进行更改并将其添加到视图中。

要解决此问题,请在函数内删除新的 texfield 对象,例如:

 private func setupViews() {

    textField.font = UIFont.systemFont(ofSize: 100.0)
    textField.textColor = .white

    backgroundColor = .black.withAlphaComponent(0.7)
    clipsToBounds = true
    layer.cornerRadius = 16.0
    // Paint stays behind it
    layer.zPosition = 1

    addSubview(textField)
    textField.snp.makeConstraints { make in
        make.edges.equalToSuperview().inset(16.0)
    }
}

或将 class 中的文本字段对象等同于您在此函数中创建的对象,如

 private func setupViews() {
    let textField = UITextField()

    textField.font = UIFont.systemFont(ofSize: 100.0)
    textField.textColor = .white

    backgroundColor = .black.withAlphaComponent(0.7)
    clipsToBounds = true
    layer.cornerRadius = 16.0
    // Paint stays behind it
    layer.zPosition = 1
    self.textField = textField // add this
    addSubview(self.textField) // change this
    textField.snp.makeConstraints { make in
        make.edges.equalToSuperview().inset(16.0)
    }
}

annotateTextField.textField's frame is zero because you are creating a new textfield and you are setting constraint to that textfield in function