2010-06-08 60 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; 
    } 
}