簡體   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