I want user to not use any extra spaces in the text field. How to do that?
Description : I have a text field which I am using for "Title of Something". I don't want to allow any user to give 开发者_如何学JAVAextra spaces/only spaces.
Regards
Here small snippet for UITextFieldDelegate:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([[textField text] length] > 0) {
if([[textField text] characterAtIndex:([[textField text] length]-1)] == ' ' &&
[string isEqualToString:@" "]) return NO;
}
return YES;
}
You can trim the string when received:
NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(trimmedString)
Also if you want to remove any double spaces inside the string i think this would do the trick:
NSString *noSpaces = [[string componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: @" "];
just try this
NSString *t1= [txt.text stringByReplacingOccurrencesOfString:@" " withString:@""]
精彩评论