user5513630 user5513630 - 7 months ago 38
Swift Question

Text field not deleting the data when i press `X` button in keyboard

I have 4

UItextfield
for enter the top number. Like 1 2 3 4. When I enter the top number in my all text field, and if I am in last urtext field - and if I press backward button or x key in my key board - My number are in each text field are not getting deleted. I was not able to delete.

Here is my code :

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

let value = textField.text!
let length = value.characters.count
if (length == 1) {
return false
}
if (textField == Field1) {
self.performSelector(Selector("setNextResponder:"), withObject: Field2, afterDelay: 0.2)
textField1 = string
} else if (textField == Field2) {
self.performSelector(Selector("setNextResponder:"), withObject: Field3, afterDelay: 0.2)
textField2 = string
} else if (textField == Field3) {
self.performSelector(Selector("setNextResponder:"), withObject: Field4, afterDelay: 0.2)
textField3 = string
} else if (textField == Field4) {
textField.resignFirstResponder()
textField4 = string
nextButton.enabled = true
}

else if (textField == Field4)
{
if string == "" && textField.text?.characters.count == 1 {
Field1.text = ""
Field2.text = ""
Field3.text = ""
Field4.text = ""
Field1.becomeFirstResponder()
}
}


return true
}


What i am missing?

Answer

You can make it like this:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

if textField.text?.characters.count == 1 && string == "" {
    if textField == txt2 {
        txt2.text = ""
        txt1.becomeFirstResponder()
    } else if textField == txt3 {
        txt3.text = ""
        txt2.becomeFirstResponder()
    } else if textField == txt4 {
        txt4.text = ""
        txt3.becomeFirstResponder()
    }
}
return true

}

Still if possible you should create a separate button with clearText action to clear all textfield instead of clearing the textfield from the clear button. It will look as better UI/UX as per the default iOS clear button behaviour