Reputation: 733
I have a UITextField and I want to allow user enter in this field maximum 2 whitespace. How I can do it?
I think I need to check something here:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {}
But what to check? I have searched the web, but nothing found.
Upvotes: 0
Views: 839
Reputation: 17622
You want to use a regular expression for this. The expression \s\s+
means two or more spaces, carriage returns or tabs.
NSString *text = textField.text;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:
@"(\s\s+)" options:0 error:nil];
[regex replaceMatchesInString:str options:0 range:NSMakeRange(0, [str length]) withTemplate:@" "];
textField.text = text;
Upvotes: 2
Reputation: 2575
This will return how many spaces there are in the string
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
int numberOfSpaces = [[textField.text componentsSeparatedByString:@" "] count];
if (numberOfSpace > 2) {
//notify user that he/she has too many spaces
}
}
Also you seem new to iOS. Don't forget to set your view controller as a UITextField delegate.
Upvotes: 1