在使用AppStorage之前,应该使用@ObservedObject或@StateObject来为视图绑定数据,例如:
struct ContentView: View { @ObservedObject var userSettings = UserSettings() var body: some View { NavigationView { VStack { Text("Hello, World!") NavigationLink(destination: DetailView(userSettings: self.userSettings)) { Text("Go to detail") } } } } }
class UserSettings: ObservableObject { @Published var isActivated = false }
struct DetailView: View { @ObservedObject var userSettings: UserSettings var body: some View { VStack { Text("Detail View") Toggle(isOn: $userSettings.isActivated) { Text("Activate feature") } } } }
在这个例子中,我们使用@ObservedObject为UserSettings创建了一个观察对象。这样,只要UserSettings对象的@Published属性发生更改,观察对象就会自动重新加载,从而更新相关的界面元素。这比使用AppStorage更可靠,因为它允许我们在单击/滑动屏幕时保留NavigationLink的状态。