[英]Why is my Switch always off when the controller is presented?
I made a SwitchRow with Eureka but can't get it to work that my switch saves it current state.我用Eureka制作了一个SwitchRow ,但无法让它工作,因为我的开关保存了它的当前状态。 It is always shown as off when the SettingsView is presented modally.
当SettingsView以模态呈现时,它始终显示为关闭。 It is a little bit irritating because I save the row value to the UserDefaults and you can't tell if it is on or not.
这有点令人恼火,因为我将行值保存到UserDefaults并且您无法判断它是否打开。 Here is my code:
这是我的代码:
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")
}
This creates a switch which changes the title if the user turns it off or on.这将创建一个开关,如果用户将其关闭或打开,则该开关会更改标题。 But the ui changes are not reflected.
但是 ui 的变化没有反映出来。 I thought the best way would be to check for the switch row itself and change its value depending on the 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
}
but this changes nothing.但这没有任何改变。
Any suggestions?有什么建议? Thanks in advance.
提前致谢。
You need to define the row.value
Therefore making your code similar to;您需要定义
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")
}
This will ensure the correct value on viewDidLoad()
.这将确保
viewDidLoad()
上的值正确。
Your second code block, the one that evalutes row.value
to be true or not will always return false given the standard state of the SwitchRow
is false.你的第二个代码块,在一个演算值为
row.value
是真实的或者是给定的标准状态并不总是会返回false SwitchRow
是假的。
Making it simple your row value is not getting updated简化您的行值不会更新
print(row.value)
You are getting every time true so your switch always on你每次都得到真实所以你的开关总是打开
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.