在 ViewController 重新出现时保留价值的正确方法
Proper way to retain value in a ViewController for when it re-appears
我有两个 ViewController:MainVC
和 SettingsVC
。
MainVC
的行为取决于运行时在 SettingsVC
中设置的值。当从 SettingsVC
转到 MainVC
时,我通过 prepareForSegue()
传递值。没问题!
但是当再次加载 SettingsVC
以再次设置该值时,最好的设置方法是什么还记得它的最后一个值吗?
是否可以创建全局变量,MainVC
和SettingsVC
都可以访问它?
是的,您可以在 class 之外使用 let
来使该变量成为全局变量。假设您的 MainVC
中有此代码
import UIKit
var param = 1
class MainVC: UIViewController {
...
}
那么这个可变参数在你的settingVC中是可见的。
但是,更好的做法是通过 segue 传递变量。当您转到 SettingVC
时,只需通过 prepareForSegue()
从 MainVC
传回设置值。如果你想在 segue 返回时传递值,你正在寻找一个 unwind segue。 Here 是一个教程。
您可以使用 UserDefaults
来达到这个目的。
An interface to the user's defaults database, where you store
key-value pairs persistently across invocations of your app on a given
device.
segue时,设置值:
// someVariable is the value you want to set
// someKey is the key to identify the value for the userDefault
UserDefaults.standard.set(someVariable, forKey: "someKey")
无论何时(从应用程序中的任何位置)获取值,请使用以下命令:
let value = UserDefaults.standard.value(forKey: "someKey")
我有两个 ViewController:MainVC
和 SettingsVC
。
MainVC
的行为取决于运行时在 SettingsVC
中设置的值。当从 SettingsVC
转到 MainVC
时,我通过 prepareForSegue()
传递值。没问题!
但是当再次加载 SettingsVC
以再次设置该值时,最好的设置方法是什么还记得它的最后一个值吗?
是否可以创建全局变量,MainVC
和SettingsVC
都可以访问它?
是的,您可以在 class 之外使用 let
来使该变量成为全局变量。假设您的 MainVC
import UIKit
var param = 1
class MainVC: UIViewController {
...
}
那么这个可变参数在你的settingVC中是可见的。
但是,更好的做法是通过 segue 传递变量。当您转到 SettingVC
时,只需通过 prepareForSegue()
从 MainVC
传回设置值。如果你想在 segue 返回时传递值,你正在寻找一个 unwind segue。 Here 是一个教程。
您可以使用 UserDefaults
来达到这个目的。
An interface to the user's defaults database, where you store key-value pairs persistently across invocations of your app on a given device.
segue时,设置值:
// someVariable is the value you want to set
// someKey is the key to identify the value for the userDefault
UserDefaults.standard.set(someVariable, forKey: "someKey")
无论何时(从应用程序中的任何位置)获取值,请使用以下命令:
let value = UserDefaults.standard.value(forKey: "someKey")