如何快速检查文本字段是否为空 [英] How to check if a text field is empty or not in swift

查看:41
本文介绍了如何快速检查文本字段是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写下面的代码来检查 textField1textField2 文本字段是否有任何输入.

I am working on the code below to check the textField1 and textField2 text fields whether there is any input in them or not.

当我按下按钮时,IF 语句没有做任何事情.

The IF statement is not doing anything when I press the button.

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

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

  //then do something

      }  
  }

推荐答案

简单地将文本字段 object 与空字符串 "" 进行比较不是正确的方法这个.您必须比较文本字段的 text 属性,因为它是一种兼容类型并保存了您要查找的信息.

Simply comparing the textfield object to the empty string "" is not the right way to go about this. You have to compare the textfield's text property, as it is a compatible type and holds the information you are looking for.

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

Swift 2.0:

守卫:

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

如果:

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

Swift 3.0:

守卫:

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

如果:

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

这篇关于如何快速检查文本字段是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆