基本上,我们现在得到的是一个按钮,该按钮根据是否填写了TextField来更改其颜色(灰色和绿色)...现在,我想添加一个也必须打开的开关让按钮的颜色变为绿色,如果没有,则变回灰色。 我如何准确地实现这一部分? PS:在viewDidLoad()中调用setupAddTargetIsNotEmptyTextFields()
func setupAddTargetIsNotEmptyTextFields() {
self.textField_username.addTarget(self, action: #selector(textFieldsIsNotEmpty), for: .editingChanged)
self.textField_eMail.addTarget(self, action: #selector(textFieldsIsNotEmpty),
for: .editingChanged)
self.textField_password.addTarget(self, action: #selector(textFieldsIsNotEmpty), for: .editingChanged)
self.textField_confirmPassword.addTarget(self, action: #selector(textFieldsIsNotEmpty),
for: .editingChanged)
}
@objc func textFieldsIsNotEmpty(sender: UITextField) {
sender.text = sender.text?.trimmingCharacters(in: .whitespaces)
guard
let username = self.textField_username.text, !username.isEmpty,
let eMail = self.textField_eMail.text, !eMail.isEmpty,
let password = self.textField_password.text, !password.isEmpty,
let confirmPassword = self.textField_confirmPassword.text,
password == confirmPassword
else
{
//button is gray
self.button_register.backgroundColor = UIColor(red:0.20, green:0.29, blue:0.37, alpha:1.0)
return
}
//button is green
self.button_register.backgroundColor = UIColor(red:0.10, green:0.74, blue:0.61, alpha:1.0)
}
答案 0 :(得分:0)
当我仅将开关添加到列表中时,我首先在textFields中输入所有内容,然后启用该开关。此时按钮仍为灰色。然后,我必须首先在文本字段中再次更改某些内容才能使其正常工作。
听起来好像正在发生的事情是,开关未设置为以文本字段的方式触发textFieldsIsNotEmpty
操作。您可以轻松地解决该问题:只需将开关配置为也可以调用该操作:
func setupAddTargetIsNotEmptyTextFields() {
self.textField_username.addTarget(self, action: #selector(textFieldsIsNotEmpty), for: .editingChanged)
// ...yada yada yada...
self.switch_selfDestructEnable.addTarget(self, action: #selector(textFieldsIsNotEmpty), for: .valueChanged)
}
现在,当值的更改像文本字段一样时,开关将发送textFieldsIsNotEmpty
。接下来,修改textFieldsIsNotEmpty()
,以检查开关的状态以及各个文本字段的状态,然后应该获得所需的行为。