我正在编写下面的代码,以检查textField1和textField2文本字段中是否有任何输入。
当我按下按钮时,IF语句不会做任何事情。
@IBOutlet var textField1 : UITextField = UITextField()
@IBOutlet var textField2 : UITextField = UITextField()
@IBAction func Button(sender : AnyObject)
{
if textField1 == "" || textField2 == ""
{
//then do something
}
}发布于 2014-06-08 03:35:46
简单地将textfield对象与空字符串""进行比较并不是正确的方法。您必须比较textfield的text属性,因为它是一个兼容的类型,并保存您正在寻找的信息。
@IBAction func Button(sender: AnyObject) {
if textField1.text == "" || textField2.text == "" {
// either textfield 1 or 2's text is empty
}
}SWIFT2.0:
警卫
guard let text = descriptionLabel.text where !text.isEmpty else {
return
}
text.characters.count //do something if it's not emptyif
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 emptyif
if let text = descriptionLabel.text, !text.isEmpty
{
//do something if it's not empty
text.characters.count
}发布于 2014-12-08 10:35:32
更好更美的用途
@IBAction func Button(sender: AnyObject) {
if textField1.text.isEmpty || textField2.text.isEmpty {
}
}发布于 2015-09-24 11:54:14
另一种签入实时textField源代码的方法:
@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
}
}https://stackoverflow.com/questions/24102641
复制相似问题