如何删除 inputAccessoryView 并将其替换为另一个视图?

How to remove inputAccessoryView and replace it with another view?

这里是要求

我试过的

这是我添加第一个输入附件视图的方法

lazy var customInputAccessoryViewNumberOne: KeyboardView = {
        let civ = KeyboardView(frame: .init(x: 0, y: 0, width: view.frame.width, height: 50))
        civ.sendButton.addTarget(self, action: #selector(handleSend), for: .touchUpInside)
        return civ
    }()

override var inputAccessoryView: UIView? {
        get {
             return customInputAccessoryViewNumberOne
        }
    }

现在当用户点击一个按钮时,我需要customInputAccessoryViewNumberTwo

完全替换customInputAccessoryViewNumberOne
@objc func handleNewInputAccessoryViewPressed() {
  //how to remove customInputAccessoryViewNumberOne?
  //how to add customInputAccessoryViewNumberTwo?
}

只需两步即可完成

第 1 步:

满足条件时设置输入附件视图

第 2 步:

在您的 UITextFieldUITextView 实例上调用 reloadInputViews()

以下代码片段对此进行了解释。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let finalText = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
    
    guard let txt = finalText else { return true }
    if txt.count > 5 {
        let greenView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40))
        greenView.backgroundColor = .green
        textField.inputAccessoryView = greenView
    } else {
        let redView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40))
        redView.backgroundColor = .red
        textField.inputAccessoryView = redView
    }
    textField.reloadInputViews()
    return true
}

显然,每次键盘出现或消失时都会调用覆盖方法(并且在出现或消失时会多次调用它,以便根据键盘的当前位置呈现视图) . 我们可以通过返回适当的 UIView().

override var inputAccessoryView 方法中使用简单的标志和 if 语句替换输入附件

-要关闭或显示键盘以便更改视图,请使用 willBecomeFirstResponderresignFirstResponder