我希望用户不要在文本字段中使用任何额外的空格。怎么做?
描述:我有一个文本字段,我用于“标题的东西”。我不想让任何用户提供额外的空格/仅空格。
此致
答案 0 :(得分:3)
这里是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;
}
答案 1 :(得分:2)
收到后可以修剪字符串:
NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(trimmedString)
另外如果你想删除字符串中的任何双重空格,我认为这样做可以解决问题:
NSString *noSpaces = [[string componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: @" "];
答案 2 :(得分:1)
试试这个
NSString *t1= [txt.text stringByReplacingOccurrencesOfString:@" " withString:@""]