在我正在开发的应用程序中,有一个电子邮件地址和密码UITextField。
我正在尝试设置条件,以便在按下SignIn
按钮时其中一个或两个都为空("(,则占位符文本应为红色,突出显示给用户以完成它们。
我对iOS开发(或一般开发(非常陌生,所以我的逻辑思维可能是错误的。 无论如何,这是我写的和开始的:
@IBAction func signInTapped(_ sender: Any) {
if emailField.text == "" {
emailField.attributedPlaceholder = NSAttributedString(string: "Email address", attributes: [NSForegroundColorAttributeName: UIColor.red])
if pwdField.text == "" {
pwdField.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName: UIColor.red])
}
}else {
这在以下情况下非常有效: -
两个字段均为空
- 电子邮件地址为空且密码字段已填写
但是...如果"电子邮件地址"字段已填充且"密码"字段为空,则"密码字段占位符"文本不会更改。
我很想知道我哪里出错了,或者是否有更简单/合乎逻辑的方法来实现结果。
我不喜欢 swift 对{}
的方式,所以对于这个例子,我向他们展示了不同的。
具有不同缩进的代码:
@IBAction func signInTapped(_ sender: Any)
{
if emailField.text == ""
{
emailField.attributedPlaceholder = NSAttributedString(string: "Email
address", attributes: [NSForegroundColorAttributeName:
UIColor.red])
if pwdField.text == ""
{
pwdField.attributedPlaceholder = NSAttributedString(string:
"Password", attributes: [NSForegroundColorAttributeName:
UIColor.red])
}
}
else {
请注意if
语句的嵌套方式。 除非emailField
为空,否则不会检查pwdField
。
要修复它,请将它们解绑并注意我移动了else
并将其变成了else if
,
固定代码:
@IBAction func signInTapped(_ sender: Any)
{
if emailField.text == ""
{
emailField.attributedPlaceholder = NSAttributedString(string: "Email
address", attributes: [NSForegroundColorAttributeName:
UIColor.red])
}
if pwdField == ""
{
pwdField.attributedPlaceholder = NSAttributedString(string:
"Password", attributes: [NSForegroundColorAttributeName:
UIColor.red])
}
else if emailField.text != ""
{
//here both fields have text inside them
}
}
你在另一个 if 语句中有一个 If 语句。
取而代之的是:
if emailField.text == "" {
emailField.attributedPlaceholder = NSAttributedString(string: "Email address", attributes: [NSForegroundColorAttributeName: UIColor.red])
if pwdField.text == "" {
pwdField.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName: UIColor.red])
}
}
使用这个:
if emailField.text == "" {
emailField.attributedPlaceholder = NSAttributedString(string: "Email address", attributes: [NSForegroundColorAttributeName: UIColor.red])
}
if pwdField.text == "" {
pwdField.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName: UIColor.red])
}
希望这有帮助!