2011-08-05 8 views
0

テキストフィールドに余分なスペースを入れないようにします。どうやってするか?iPhoneアプリケーションのTextFieldスペースの検証

概要「Title of Something」に使用しているテキストフィールドがあります。私は、余分なスペース/スペースのみをユーザーに許可したくありません。

よろしく

答えて

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; 
} 
+0

超回答!!素晴らしい仕事! –

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: @" "]; 
+1

を試してみてください(私はログにそれを印刷していますが、それは私に同じ文字列を与えています。) – Akshay

+0

あなたのコードというの一部を共有することができますこれは? –

1

ちょうどそれが私のために働いていない理由を私は知らないのですか?この

NSString *t1= [txt.text stringByReplacingOccurrencesOfString:@" " withString:@""] 
関連する問題