iPhone应用程序中的文本字段空间验证

iPhone应用程序中的文本字段空间验证,iphone,ios,ipad,validation,space,Iphone,Ios,Ipad,Validation,Space,我希望用户不要在文本字段中使用任何额外的空格。怎么做 描述:我有一个文本字段,用于“某物的标题”。我不想允许任何用户提供额外的空间/仅提供空间 关于您可以在收到时修剪字符串: NSString *string = @" spaces in front and at the end "; NSString *trimmedString = [string stringByTrimmingCharactersInSet: [NSCharac

我希望用户不要在文本字段中使用任何额外的空格。怎么做

描述:我有一个文本字段,用于“某物的标题”。我不想允许任何用户提供额外的空间/仅提供空间


关于

您可以在收到时修剪字符串:

NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                              [NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(trimmedString)
另外,如果要删除字符串中的任何双空格,我认为这样做可以达到以下目的:

NSString *noSpaces = [[string componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: @" "];

您可以在收到以下内容时修剪字符串:

NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                              [NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(trimmedString)
另外,如果要删除字符串中的任何双空格,我认为这样做可以达到以下目的:

NSString *noSpaces = [[string componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: @" "];

以下是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;
}

以下是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;
}
试试这个

 NSString *t1= [txt.text stringByReplacingOccurrencesOfString:@" " withString:@""]
试试这个

 NSString *t1= [txt.text stringByReplacingOccurrencesOfString:@" " withString:@""]

我不知道为什么它对我不起作用?(我在日志中打印它,但它给了我相同的字符串。)我不知道为什么它对我不起作用?(我在日志中打印它,但它给了我相同的字符串。)