基本上,我们现在得到的是一个按钮,该按钮可以根据是否填充了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)
}
最佳答案
当我只将开关添加到列表中时,我首先在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()
来检查开关的状态以及各个文本字段的状态,然后应该获得所需的行为。关于swift - Xcode/Swift |知道是否随时打开UISwitch,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52846086/