[英]TextField Space Validation in iPhone App
我希望用戶不要在文本字段中使用任何多余的空格。 怎么做?
描述:我有一個文本字段,用於“某事的標題”。 我不想允許任何用戶提供額外的空格/僅空格。
問候
這里是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 *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(trimmedString)
另外,如果您想刪除字符串中的所有雙精度空格,我認為這可以解決問題:
NSString *noSpaces = [[string componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: @" "];
試試這個
NSString *t1= [txt.text stringByReplacingOccurrencesOfString:@" " withString:@""]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.