-2
我有一个注册视图控制器,它可以:1)在用户有他的提交按钮之后,一个空的文本框文本为红色; 2)使用UIView来摇动空的文本框。Swift If语句
// if registered button is clicked and textfields are empty
if usernameTxt.text!.isEmpty || passwordTxt.text!.isEmpty || emailTxt.text!.isEmpty || fullnameTxt.text!.isEmpty {
// display red placeholders for empty textfields
usernameTxt.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSForegroundColorAttributeName: UIColor.red])
passwordTxt.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName: UIColor.red])
emailTxt.attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSForegroundColorAttributeName: UIColor.red])
fullnameTxt.attributedPlaceholder = NSAttributedString(string: "Full Name", attributes:
[NSForegroundColorAttributeName: UIColor.red])
}
// shake username textfield if it is empty
if usernameTxt.text == "" {
usernameTxt.shake()
}
// shake password textfield if it is empty
if passwordTxt.text == "" {
passwordTxt.shake()
}
// shake email textfield if it is empty
if emailTxt.text == "" {
emailTxt.shake()
}
// shake fullname textfield if it is empty
if fullnameTxt.text == "" {
fullnameTxt.shake()
}
} else {
// remove keyboard
self.view.endEditing(true)
}
但是,如果文本框为空,但仍执行红色的占位符文本以及文本字段抖动但毕竟它也执行代码“}其他{”
有没有人有任何建议重新编写这段代码,以便在else之后的代码不被执行?在此先感谢
你的代码有问题......括号不对齐。事实上,你并没有显示其他语句的第一条语句,因此不可能重写。如果你希望else只在其他字段不为空的情况下执行:如果检查是否为空,则将if放在第一个字符中,并且其他字符应附加到它的语句中,而目前它不是。 –
我刚编辑你的if语句来添加适当的缩进。 @EvanCarslake是正确的 - 没有任何符合'else'。你是否错过了“顶级”?就目前而言,唯一有意义的是将另一个4个空格的“else”上面的所有内容缩进去。 – dfd
对不起,我删除了一些冗余代码,使其更短。忘了取下支架 – codeislife