user3613119
user3613119

Reputation: 91

Check if UITextField have a leading whitespace

I have a TextField called myTextField, and I need to check two things:

For that I try this:

if ([myTextField.text isEqualToString:@""]){

//My code

}

This check if the textField is empty, but how I can check if the first letter is no a whitespace ?

Upvotes: 0

Views: 366

Answers (1)

Popeye
Popeye

Reputation: 12093

To check that there is no whitespace and to check that it is NOT empty try the below, note the ! is basically saying if((myTextField is not empty) && (myTextField does not have a prefix of " "))

if(![myTextField.text isEqualToString:@""] && ![myTextField.text hasPrefix:@" "]) {
    // Do whatever you want
} else if(![myTextField.text isEqualToString:@""] && [myTextField.text hasPrefix:@" "]) {
    // Do whatever we want to remove whitespace, you can use `stringByTrimmingCharactersInSet:` to remove white space   
} else {
    // Else do what you want if nothing else matches.
}

Upvotes: 1

Related Questions