user3746428
user3746428

Reputation: 11175

Removing whitespace while typing into text field

I have just added a text field that allows users to input recipients email addresses before within the app rather than within the email view.

I want to restrict users from entering spaces so that they can't input invalid email addresses.

This is the code I came up with but it doesn't do anything when run:

func textFieldDidChange(textField: UITextField) {
    var text = emailText.text.stringByReplacingOccurrencesOfString(" ", withString: "")
    emailText.text = text
}

How can I replace any instances of whitespace while the user is typing?

Upvotes: 1

Views: 3294

Answers (1)

nhgrif
nhgrif

Reputation: 62052

You have to add that method as a target for events of the text field. In your viewDidLoad, add this line:

yourTextField.addTarget(self, 
    action: "textFieldDidChange", 
    forControlEvents: .EditingChanged
)

Alternatively, and perhaps better, you could set your view controller to be the text field's delegate:

yourTextField.delegate = self

And then implement the following text field delegate method:

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

If the replacement string contains white space, return false.

Also, consider there are white space characters other than just a simple space. You probably want to check the replacement string against NSCharacterSet.whitespaceCharacterSet()

Upvotes: 4

Related Questions