Trim Whitespace From UITextField in Swift

Let’s say you have a text field and you want to disable the Save button until the user enters something. But you don’t want to allow whitespaces. Here’s one way to handle that.

1. Hook up an outlet to your bar button item so you can set its isEnabled state later.

@IBOutlet weak var saveButton: UIBarButtonItem!

2. Hook up an outlet to your text field.

@IBOutlet weak var nameTextField: UITextField!

3. Set a target action on your text field. Put this in your viewDidLoad method.

nameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)

4. Create the selector method.

@objc private func textFieldDidChange(_ textField: UITextField) {
    guard let text = textField.text else { return }

    if !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
        saveButton.isEnabled = true

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.