Search code examples
swifttextfieldnsnotificationsuiresponder

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


I have a function firing on two observers - keyboardWillShowNotification and KeyboardWillHideNotification, and what I basically do is resetting a text field while editing, emulating the effect of clearsOnBeginEditing. However, if the user left the field blank I want it to return the original value, before editing. Here's my experimental code:

@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")

                        }
                }
            }
    }

What's the right way to do it?


Solution

  • You do not need to implement keyboard delegates for this. This is easily acheivable using the UITextFieldDelegate methods textFieldDidBeginEditing and textFieldDidEndEditing.

    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
        }
    }
    

    Note: Your view controller would need to conform to UITextFieldDelegate and your text fields should have their delegates set to self.