Check if a UITextField is empty

This content has 9 years. Please, read this page keeping its age in your mind.

One of the most common tasks is to check whether a UITextField is empty in order to proceed with a save action. The way to manage the Return Key in the keyboard is very easy. In the Attributes Inspector of the UITextField object you just have to enable the “Auto-enable Return Key” option.

textField

On the other hand what we should do if we have a Bar Button that needs to be enabled or disabled according to the text field. This is a bit more complex. In this case we need to check the contents of the text field after every keystroke.

Since the ViewController is the delegate of the UITextField we can use the following method:

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

This method is called whenever the user changes the text either using the keyboard or cut and paste. This methods seems complicated until we clarify the parameters.

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

let beforeText: NSString = textField.text
let afterText: NSString = beforeText.stringByReplacingCharactersInRange(range, withString: string)

if afterText.length > 0 {
okBarButton.enabled = true
} else {
okBarButton.enabled = false
}

return true
}

The actual contents of the textField.text are the text before the users modifications. To get the new text after the user’s intervention we need to use stringByReplacingCharactersInRange(range: NSRange, withString replacement: String) -> String method giving the range and the replacement string. Both of these parameters are known. Eventually, the new text is the afterText NSString and checking its value can help us to enable or disable the appropriate button.