web-dev-qa-db-fra.com

Comment vérifier si un champ de texte est vide ou non dans swift

Je travaille sur le code ci-dessous pour vérifier le textField1 et textField2 _ les champs de texte, qu’il y ait ou non une entrée.

L'instruction IF ne fait rien lorsque j'appuie sur le bouton.

 @IBOutlet var textField1 : UITextField = UITextField()
 @IBOutlet var textField2 : UITextField = UITextField()
 @IBAction func Button(sender : AnyObject) 
  {

    if textField1 == "" || textField2 == "" 
      {

  //then do something

      }  
  }
49
Gokhan Dilek

En comparant simplement l'objet textfield à la chaîne vide "" n'est pas la bonne façon de s'y prendre. Vous devez comparer la propriété text du champ de texte, car il s'agit d'un type compatible qui contient les informations que vous recherchez.

@IBAction func Button(sender: AnyObject) {
    if textField1.text == "" || textField2.text == "" {
        // either textfield 1 or 2's text is empty
    }
}

Swift 2.0:

Garde:

guard let text = descriptionLabel.text where !text.isEmpty else {
    return
}
text.characters.count  //do something if it's not empty

si:

if let text = descriptionLabel.text where !text.isEmpty
{
    //do something if it's not empty  
    text.characters.count  
}

Swift 3.0:

Garde:

guard let text = descriptionLabel.text, !text.isEmpty else {
    return
}
text.characters.count  //do something if it's not empty

si:

if let text = descriptionLabel.text, !text.isEmpty
{
    //do something if it's not empty  
    text.characters.count  
}
157
Brian Tracy

Meilleure et plus belle utilisation

 @IBAction func Button(sender: AnyObject) {
    if textField1.text.isEmpty || textField2.text.isEmpty {

    }
}
48
UnRewa

une autre façon d’enregistrer les sources textField en temps réel:

 @IBOutlet var textField1 : UITextField = UITextField()

 override func viewDidLoad() 
 {
    ....
    self.textField1.addTarget(self, action: Selector("yourNameFunction:"), forControlEvents: UIControlEvents.EditingChanged)
 }

 func yourNameFunction(sender: UITextField) {

    if sender.text.isEmpty {
      // textfield is empty
    } else {
      // text field is not empty
    }
  }
11
raphael

si laisser ... où ... {

Swift:

if let _text = theTextField.text, _text.isEmpty {
    // _text is not empty here
}

Swift 2:

if let theText = theTextField.text where !theTextField.text!.isEmpty {
    // theText is not empty here
}

garde ... où ... sinon {

Vous pouvez également utiliser le mot-clé guard:

Swift:

guard let theText = theTextField.text where theText.isEmpty else {
    // theText is empty
    return // or throw
}

// you can use theText outside the guard scope !
print("user wrote \(theText)")

Swift 2:

guard let theText = theTextField.text where !theTextField.text!.isEmpty else {
    // the text is empty
    return
}

// you can use theText outside the guard scope !
print("user wrote \(theText)")

Ceci est particulièrement intéressant pour les chaînes de validation, dans les formulaires par exemple. Vous pouvez écrire un guard let pour chaque validation et renvoie ou renvoie une exception en cas d'erreur critique.

5
Alexandre G.

Comme maintenant dans Swift 3/xcode 8, la propriété de texte est optionnelle, vous pouvez le faire comme ceci:

if ((textField.text ?? "").isEmpty) {
    // is empty
}

ou:

if (textField.text?.isEmpty ?? true) {
    // is empty
}

Alternativement, vous pouvez faire une extension comme celle ci-dessous et l'utiliser à la place:

extension UITextField {
    var isEmpty: Bool {
        return text?.isEmpty ?? true
    }
}

...

if (textField.isEmpty) {
    // is empty
}
5
Leszek Szary

Un petit bijou compact pour Swift 2/Xcode 7

@IBAction func SubmitAgeButton(sender: AnyObject) {

    let newAge = String(inputField.text!)        

if ((textField.text?.isEmpty) != false) {
        label.text = "Enter a number!"
    }
    else {
        label.text = "Oh, you're \(newAge)"

        return
    }

    }
4
tymac

Peut-être que je suis un peu en retard, mais ne pouvons-nous pas vérifier comme ceci:

   @IBAction func Button(sender: AnyObject) {
       if textField1.text.utf16Count == 0 || textField2.text.utf16Count == 0 {

       }
    }
3
jfredsilva

D'accord, cela pourrait être tard, mais dans Xcode 8, j'ai une solution:

if(textbox.stringValue.isEmpty) {
    // some code
} else {
    //some code
}
2
Corey Kennedy

Swift 4/xcode 9

IBAction func button(_ sender: UIButton) {
        if (textField1.text?.isEmpty)! || (textfield2.text?.isEmpty)!{
                ..............
        }
}
1
gii96

J'ai utilisé la fonctionnalité intégrée de UIKeyInputhasText: docs

Pour Swift 2.3, je devais l'utiliser comme méthode plutôt que comme une propriété (comme il est référencé dans la documentation):

if textField1.hasText() && textField2.hasText() {
    // both textfields have some text
}
0
Alex Brashear

C'est trop tard et ça marche très bien dans Xcode 7.3.1

if _txtfield1.text!.isEmpty || _txtfield2.text!.isEmpty {
        //is empty
    }
0
joel prithivi

Swift 4.2

Vous pouvez utiliser une fonction générale pour chaque textField. Ajoutez simplement la fonction suivante dans votre contrôleur de base.

// White space validation.
func checkTextFieldIsNotEmpty(text:String) -> Bool
{
    if (text.trimmingCharacters(in: .whitespaces).isEmpty)
    {
        return false

    }else{
        return true
    }
}
0
Rana Ali Waseem

Je viens d'essayer de vous montrer la solution dans un code simple

@IBAction func Button(sender : AnyObject) {
 if textField1.text != "" {
   // either textfield 1 is not empty then do this task
 }else{
   //show error here that textfield1 is empty
 }
}
0
Naveed Ahmad

Swift 4.x Solution


@IBOutlet var yourTextField: UITextField!

 override func viewDidLoad() {
     ....
     yourTextField.addTarget(self, action: #selector(actionTextFieldIsEditingChanged), for: UIControlEvents.editingChanged)
  }

 @objc func actionTextFieldIsEditingChanged(sender: UITextField) {
     if sender.text.isEmpty {
       // textfield is empty
     } else {
       // text field is not empty
     }
  }
0
Hemang