Objetivo c comprobar si el campo de texto está vacío


Aquí está el código:

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

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

Esto lo envía incluso cuando el campo está vacío; por lo tanto, esto no funciona como quiero.

Author: objectiveccoder001, 2010-07-04

6 answers

Simplemente comprueba si la longitud del texto es mayor que 0 - no está vacía

if (textField.text && textField.text.length > 0)
{
   /* not empty - do something */
}
else
{
   /* what ever */
}
 82
Author: Joshua Weinberg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-13 19:02:36

Ya tenemos un método incorporado que devuelve un valor booleano que indica si los objetos de entrada de texto tienen texto o no.

// 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 */
}
 51
Author: Gaurav Pandey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-14 05:56:11

Joshua tiene la respuesta correcta en el caso estrecho, pero generalmente, no se pueden comparar objetos de cadena usando = = or != operador. Debes usar -isEqual: o -isEqualToString: Esto se debe a que charlieImputSelf y @"" son en realidad punteros a objetos. Aunque las dos secuencias de caracteres pueden ser iguales, no es necesario que apunten a la misma ubicación en la memoria.

 6
Author: JeremyP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-04 12:19:36

Esos 'funcionan' de alguna manera. Sin embargo, encontré que el usuario solo puede llenar la caja con espacios. Descubrí que usar expresiones regulares ayuda (aunque lo que uso es para palabras sin espacios) Realmente no puedo averiguar cómo hacer espacios permitidos.

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

if (!([[inputField stringValue]isEqualTo:regex])) {
        NSLog(@"Found a match");
// Do stuff in here //
}
 2
Author: Jon Wei,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-12 22:39:49

La forma más eficaz de hacer esto es mediante el uso de este

// 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
Author: ScottMobile,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-21 19:39:31

Compruebe si el campo de texto está vacío en 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
Author: seinfeld,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-10 23:12:08