Chapter 12, Clear Button for the text field

Hi there,

just finished the 12th chapter of the book (6th edition), thanks to the competent authors everything described was very clear and helpful!

I tried to play around with the code and storyboard options, and when I enabled the Clear Button attribute of the Text Field,

TextFieldAttributes1

I realized that when we run the app and use the Clear Button to clear the textfield, ‘Done’ button remains active:

iPhoneScreenshot1

I would be grateful if someone could explain how to disable the ‘Done’ button in this case. :slight_smile:

If you recall, any data entry related activity for a UITextField is relayed via the UITextFieldDelegate. That’s how the current Done button enabling/disabling is handled too. So what you need to do is look up the documentation for UITextFieldDelegate and see if you can find a method which would handle the field contents clearing.

If you are stuck, or would rather not do the searching via documentation, then the solution appears below under the “Solution” section. But I would really encourage you to try this out on your own by looking through the documentation as I suggested - that’s the best way to grow as a developer :slight_smile:

Solution

Add the following UITextFieldDelegate method to handle the text field clearing event and to disable the Done button:

func textFieldShouldClear(_ textField: UITextField) -> Bool {
    doneBarButton.isEnabled = false
    return true
}
2 Likes

Thank you for the reply!

Following your advice, I read through the documentation for the UITextFieldDelegate and found this:

The text field calls various delegate methods during editing:
. . . . .
It calls the textFieldShouldClear(_: ) method when the user taps the built-in button to clear the text.
. . . . .

Then I looked at the code for the textField(_:shouldChangeCharactersIn:replacementString:) from the book, and just below this method I tried to add following:

func textFieldShouldClear(_ textField: UITextField) -> Bool {
    textField.text!.removeAll()
    doneBarButton.isEnabled = false
    return true
  }

and that worked.
After that I tried to delete the line:
textField.text!.removeAll()
wich also worked perfectly! :slight_smile:

So now ‘Done’ button gets also disabled when we clear the text using that button.

And after that I clicked the ‘Solution’ in your message, and found out that it’s identical! :slight_smile:
Having this experience I’ll be more attentive to the documentation.
Thank you for your time and for advice!

This topic was automatically closed after 166 days. New replies are no longer allowed.