开发者

TextField Space Validation in iPhone App

开发者 https://www.devze.com 2023-03-25 07:57 出处:网络
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 开发者

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:@""]
0

精彩评论

暂无评论...
验证码 换一张
取 消