gpt4 book ai didi

swift - Xcode/Swift |随时了解 UISwitch 是否打开

转载 作者:行者123 更新时间:2023-11-30 11:04:48 25 4
gpt4 key购买 nike

基本上,我们现在得到的是一个按钮,它根据文本字段是否填写来更改其颜色(灰色和绿色)...现在我想添加一个也必须打开的开关让按钮颜色变为绿色,如果没有,则变回灰色。我具体如何实现这部分?PS:setupAddTargetIsNotEmptyTextFields()在viewDidLoad()中调用

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)
}

最佳答案

When I just add the switch to the list, I first type in everything in the textFields and then enable the switch. At this moment the button is still gray. Then I have to first change something again in the textfields to make it work.

听起来发生的情况是开关未设置为像文本字段那样触发 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com