如果 textField 留空,如何恢复 "clearsOnBeginEditing(true) effect"(在开始编辑时删除旧值)?

How to revert the "clearsOnBeginEditing(true) effect" (remove older value at beging editing) on textField if it is left blank?

我有一个函数触发两个观察者 - keyboardWillShowNotificationKeyboardWillHideNotification,我基本上做的是在编辑时重置文本字段,模拟 clearsOnBeginEditing 的效果。但是,如果用户将该字段留空,我希望它在编辑之前 return 原始值。这是我的实验代码:

@objc func keyboardWillChange(notification: Notification) {

    if notification.name == UIResponder.keyboardWillShowNotification || notification.name == UIResponder.keyboardWillHideNotification {

            if textField.isEditing {
                let originalValue: String!
                originalValue = textField.text!
                textField.text = ""
                print("content while editing is \(originalValue)")

                if notification.name == UIResponder.keyboardWillHideNotification {
                    print("this is content on end editing \(originalValue)")

                        if textField!.isEmpty == true {
                            print("this is nill")
                            textField.text! = originalValue
                        } else {
                             textField.text = textField.text
                             print("found a value")

                        }
                }
            }
    }

正确的做法是什么?

您不需要为此实现键盘委托。使用 UITextFieldDelegate 方法 textFieldDidBeginEditingtextFieldDidEndEditing.

很容易实现这一点
var orignalValue: String = ""

func textFieldDidBeginEditing(_ textField: UITextField) {
    originalValue = textField.text
    textField.text = ""
}

func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
    if textField.text?.isEmpty {
        textField.text = orignalValue
    }
}

注意:您的视图控制器需要符合 UITextFieldDelegate 并且您的文本字段应将其委托设置为 self