验证空的UITextField?

Mos*_*she 3 iphone objective-c uitextfield ios

UITextField为空时的值是多少?我似乎无法做到这一点.

我试过(其中`phraseBox'是所说的UITextField的名字

if(phraseBox.text != @""){
Run Code Online (Sandbox Code Playgroud)

if(phraseBox.text != nil){

我错过了什么?

Rap*_*eta 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.
}
Run Code Online (Sandbox Code Playgroud)


小智 13

在寻找相同的东西时,在苹果讨论中发现了这一点,想到这里也发布了.检查字符串的长度:

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

}
Run Code Online (Sandbox Code Playgroud)

或者在验证之前可选择修剪空格,因此用户不能输入空格.对于用户名来说也很好.

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

if([value length] == 0) {
// Alert the user they forgot something
}
Run Code Online (Sandbox Code Playgroud)