如何在swift中检查文本字段是否为空

前端之家收集整理的这篇文章主要介绍了如何在swift中检查文本字段是否为空前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在下面的代码中检查textField1和textField2文本字段,无论是否有任何输入。

当我按下按钮时,IF声明没有做任何事情。

  1. @IBOutlet var textField1 : UITextField = UITextField()
  2. @IBOutlet var textField2 : UITextField = UITextField()
  3. @IBAction func Button(sender : AnyObject)
  4. {
  5.  
  6. if textField1 == "" || textField2 == ""
  7. {
  8.  
  9. //then do something
  10.  
  11. }
  12. }
简单地比较textfield对象和空字符串“”不是正确的方法。您必须比较textfield的文本属性,因为它是兼容的类型,并保存您要查找的信息。
  1. @IBAction func Button(sender: AnyObject) {
  2. if textField1.text == "" || textField2.text == "" {
  3. // either textfield 1 or 2's text is empty
  4. }
  5. }

Swift 2.0:

守卫:

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

如果:

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

Swift 3.0:

守卫:

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

如果:

  1. if let text = descriptionLabel.text,!text.isEmpty
  2. {
  3. //do something if it's not empty
  4. text.characters.count
  5. }

猜你在找的Swift相关文章