2010-06-08 59 views
3

UITextField空时的值是什么?我似乎无法得到这个权利。验证空UITextField?

我试过(其中`phraseBox”它所说的UITextField

if(phraseBox.text != @""){ 

if(phraseBox.text != nil){

我缺少什么?

+0

'[phraseBox hasText]' – ma11hew28 2014-07-17 17:34:09

回答

21
// Check to see if it's blank 
if([phraseBox.text isEqualToString:@""]) { 
    // There's no text in the box. 
} 

// Check to see if it's NOT blank 
if(![phraseBox.text isEqualToString:@""]) { 
    // There's text in the box. 
} 
+0

根据SO规则需要等待15分钟才能接受。我有13更多分钟来测试这个,嘿嘿... – Moshe 2010-06-08 23:24:08

+0

感谢您的编辑。我用'!'找出了那部分。 – Moshe 2010-06-08 23:26:59

+0

始终保持简单:) – fyasar 2014-02-03 12:58:50

1

尝试名以下代码

的TextField.text是一个字符串值,所以我们正在检查它像​​这样

if([txtPhraseBox.text isEqualToString:@""]) 

{ 

// There's no text in the box. 

} 

else 

{ 

NSLog(@"Text Field Text == : %@ ",txtPhraseBox.text); 

} 
13
同样的事情在搜索时发现这个在苹果讨论

,以为生病后在这里了。 检查字符串的长度:

NSString *value = textField.text; 
if([value length] == 0) { 

} 

或任选验证之前从它修剪空格,所以用户不能输入空格instead.works以及为用户名。

NSString *value = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 

if([value length] == 0) { 
// Alert the user they forgot something 
} 
+0

这也是苹果示例代码的解决方案。谢谢 – carbonr 2012-04-13 21:57:30

+0

当然,你不需要这么多括号:) – 2013-04-10 23:24:59

0

事实上,我遇到了使用拉斐尔的方法与多个文本字段的轻微问题。以下是我想出了:

if ((usernameTextField.text.length > 0) && (passwordTextField.text.length > 0)) { 
    loginButton.enabled = YES; 
} else { 
    loginButton.enabled = NO; 
} 
0

用于文本字段验证:

-(BOOL)validation{ 
if ([emailtextfield.text length] <= 0) { 
    [UIAlertView showAlertViewWithTitle:AlertTitle message:AlertWhenemailblank]; 
    return NO; } 
return YES;} 
1
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ 

    NSString *fullText = [textField.text stringByAppendingString:string];  
    if ((range.location == 0) && [self isABackSpace:string]) { 
    //the textFiled will be empty 
    } 
    return YES; 
} 

-(BOOL)isABackSpace:(NSString*)string { 
    NSString* check [email protected]"Check"; 
    check = [check stringByAppendingString:string]; 
    if ([check isEqualToString:@"Check"]) { 
    return YES; 
    } 
    return NO; 
} 
+0

谢谢这帮助我。 – Shivaay 2013-12-28 08:33:10

0

验证对空的UITextField。如果你不希望那个UITextField不应该接受空白的空格。使用此代码片段:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 

    NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string]; 
    NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet]; 
    if ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound)  { 
     return YES; 
    } else { 
     return NO; 
    } 
}