我正在下面的代码中检查textField1和textField2文本字段,无论是否有任何输入。
当我按下按钮时,IF声明没有做任何事情。
@IBOutlet var textField1 : UITextField = UITextField() @IBOutlet var textField2 : UITextField = UITextField() @IBAction func Button(sender : AnyObject) { if textField1 == "" || textField2 == "" { //then do something } }
简单地比较textfield对象和空字符串“”不是正确的方法。您必须比较textfield的文本属性,因为它是兼容的类型,并保存您要查找的信息。
原文链接:https://www.f2er.com/swift/320678.html@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 }