我刚刚在设置菜单的一个单元格内添加了一个 UISwitch,当我离开 View 时,我遇到了开关状态恢复为开启的问题。
我尝试添加这段代码:
override func viewDidAppear(animated: Bool) {
if autoAdjust == true {
dupSwitch.on = true
} else {
dupSwitch.on = false
}
}
虽然这确实有效,但它并不理想,因为当 View 出现时状态之间有明显的跳跃。
当用户离开 View 时,我如何确保开关保持在用户离开的任何位置?
最佳答案
How can I ensure that the switch stays in whatever position the user left it in when they leave the view?
将开关的当前状态存储在模型类中(在模型- View - Controller 的意义上)。 autoAdjust
变量的值应该保存在一个不会随 View 一起卸载的对象中 - 即在您的模型类中。
当 View 即将出现时,读取开关的当前状态,并将dupSwitch.on
设置为模型中存储的状态。
注意:为避免显示切换过程,请将您的逻辑从viewDidAppear
移至viewWillAppear
。您的代码也可以简化 - 您不需要条件:
override func viewWillAppear(animated: Bool) {
dupSwitch.on = autoAdjust
}
关于swift - 如何保持 UISwitch 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25437837/