How to know if a UITextField in iOS has blank spaces How to know if a UITextField in iOS has blank spaces ios ios

How to know if a UITextField in iOS has blank spaces


You can "trim" the text, that is remove all the whitespace at the start and end. If all that's left is an empty string, then only whitespace (or nothing) was entered.

NSString *rawString = [textField text];NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];if ([trimmed length] == 0) {    // Text was empty or only whitespace.}

If you want to check whether there is any whitespace (anywhere in the text), you can do it like this:

NSRange range = [rawString rangeOfCharacterFromSet:whitespace];if (range.location != NSNotFound) {    // There is whitespace.}

If you want to prevent the user from entering whitespace at all, see @Hanon's solution.


if you really want to 'restrict' user from entering white space

you can implement the following method in UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range     replacementString:(NSString *)string {     NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];    NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];    if  ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound)      {        return YES;    }  else  {        return NO;    } }

If user enter space in the field, there is no change in the current text


Use following lines of code

NSString *str_test = @"Example ";NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];if([str_test rangeOfCharacterFromSet:whitespaceSet].location!=NSNotFound){    NSLog(@"Found");}

if you want to restrict user use below code

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{    if([string isEqualToString:@" "])    {        return NO    }    else    {        return YES    }}


matomo