Objective-C如何检查文本框是否为空。

38

以下是代码:

- (IBAction) charlieInputText:(id)sender {
    //getting value from text field when entered
    charlieInputSelf = [sender stringValue];

    if (charlieInputSelf != @"") {
        //(send field if not empty
    }
}    

即使字段为空也会发送它;因此,这并不像我想要的那样工作。

8个回答

88

检查是否为nil,如果文本长度大于0,则不为空。

if (textField.text && textField.text.length > 0)
{
   /* not empty - do something */
}
else
{
   /* what ever */
}

15
我觉得 Stack 比任何主流平台的官方文档更能成为有用的参考资料。 - ChuckKelly
3
实际上,如果textField为nil,则textField.text.length == 0。因此,您可以将if简化为: if (textField.text.length > 0) - Victor Maia Aldecôa
两个条件是相互依赖的。只保留一个条件。因为0&0=0,1&1=1。 - Saranjith

57
我们已经有内置的方法可以返回布尔值,指示文本输入对象是否有任何文本。
// In Obj-C
if ([textField hasText]) {
        //*    Do Something you have text
    }else{
         /* what ever */
    }

// In Swift

if textField.hasText {
    //*    Do Something you have text
}else{
     /* what ever */
}

2
我不知道 hasText! - DogCoffee
let clientName = clientNameTF.hasText() ? clientNameTF.text! : "客户名称" - DogCoffee
2
这是最优雅的答案!谢谢。 - Sonic Master

8

在狭义的情况下,Joshua给出了正确的答案,但一般情况下,您不能使用==或!=运算符比较字符串对象。您必须使用-isEqual:-isEqualToString:。这是因为charlieImputSelf@""实际上是指向对象的指针。虽然这两个字符序列可能相同,但它们不一定指向内存中的相同位置。


3
如果您想检查文本字段的值是否等于“Boo”,则必须使用if([textField.text isEqualToString:@“Boo”])而不是if(textField.text == @“Boo”) - Douwe Maan
1
是的 - JeremyP

2

这些方法可以使用。不过,我发现用户可以只用空格填充框。使用正则表达式有所帮助(尽管我使用的是没有空格的单词),但我真的搞不清如何让空格作为选项。

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[ ]" options:NSRegularExpressionCaseInsensitive error:&error];

if (!([[inputField stringValue]isEqualTo:regex])) {
        NSLog(@"Found a match");
// Do stuff in here //
}

1

在Swift中检查文本字段是否为空

  @IBOutlet weak var textField: NSTextField!
  @IBOutlet weak var multiLineTextField: NSTextField!

  @IBAction func textChanged(sender: AnyObject) {
    //println("text changed! \(textField.stringValue)")

    if textField.stringValue.isEmpty == false {
      multiLineTextField.becomeFirstResponder()
      multiLineTextField.editable = true
    } else {
      multiLineTextField.editable = false
    }
  }

1
最有效的方法是使用这个。
// set it into an NSString
NSString *yourText = yourVariable.text;

if([theText length] == 0])
{
 // Your Code if it is equal to zero
}
else
{
// of the field is not empty

}

1
最简单的方法是这样做。 创建一个没有空格的新NSString。
NSString *textWithoutSpaces = [self.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

现在你有一个没有空格的字符串。你只需要检查这个字符串是否为空。
if (textWithoutSpaces != 0) {
 /* not empty - do something */
} else {
  /* empty - do something */
} 

0
-(void)insert{

    if ([_nameofView  isEqual: @""]) {
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                       message:@"Fill the Name Field First."
                                                                preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {}];

        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];



    }
    else if ([_detailofview  isEqual: @""]){

        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                       message:@"Fill the Details Field First."
                                                                preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {}];

        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];

    }
    else{
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Alert"
                                                                       message:@"Data Inserted Successfully."
                                                                preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {}];

        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];

    }
}

我建议你在回答中添加一些解释性文本,否则可能会被删除为“低质量”(即使它可能是正确的答案)! - Adrian Mole

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接