繁体   English   中英

为什么当控制器出现时我的 Switch 总是关闭?

[英]Why is my Switch always off when the controller is presented?

我用Eureka制作了一个SwitchRow ,但无法让它工作,因为我的开关保存了它的当前状态。 SettingsView以模态呈现时,它始终显示为关闭。 这有点令人恼火,因为我将行值保存到UserDefaults并且您无法判断它是否打开。 这是我的代码:

class SettingsView : FormViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
    
            +++ Section("Messages")
            <<< SwitchRow("message_people_withId") { row in
                row.title = "Activate messages"
            }.onChange { row in
                row.title = (row.value ?? false) ? "Deactivate messages" : "Activate messages"
                row.updateCell()
                UserDefaults.standard.set(row.value ?? false, forKey: "MessageSettingsRow")

            }

这将创建一个开关,如果用户将其关闭或打开,则该开关会更改标题。 但是 ui 的变化没有反映出来。 我认为最好的方法是检查开关行本身并根据行值更改其值:

 if row.value == true {
                    (self.form.rowBy(tag: "message_people_withId") as? SwitchRow)?.cell.switchControl.isOn = true
                } else {
                    (self.form.rowBy(tag: "message_people_withId") as? SwitchRow)?.cell.switchControl.isOn = false
                }

但这没有任何改变。

有什么建议? 提前致谢。

您需要定义row.value因此使您的代码类似于;

class SettingsView : FormViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
    
            +++ Section("Messages")
            <<< SwitchRow("message_people_withId") { row in
                row.title = "Activate messages"
                row.value = UserDefaults.standard.bool(forKey: "MessageSettingsRow")
            }.onChange { row in
                row.title = (row.value ?? false) ? "Deactivate messages" : "Activate messages"
                row.updateCell()
                UserDefaults.standard.set(row.value ?? false, forKey: "MessageSettingsRow")

            }

这将确保viewDidLoad()上的值正确。

你的第二个代码块,在一个演算值为row.value是真实的或者是给定的标准状态并不总是会返回false SwitchRow是假的。

简化您的行值不会更新

 print(row.value)

你每次都得到真实所以你的开关总是打开

if row.value == true {
                (self.form.rowBy(tag: "message_people_withId") as? SwitchRow)?.cell.switchControl.isOn = true
            } else {
                (self.form.rowBy(tag: "message_people_withId") as? SwitchRow)?.cell.switchControl.isOn = false
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM