如何保存@EnvironmentObject的数据? (SwiftUI)

时间:2020-09-17 18:52:28

标签: ios swift swiftui

我想保存@EnvironmentObject的数据,以便它不会删除每次启动的应用程序。

此外,我想让该应用程序在iOS 13+设备上运行,所以我不能使用新的属性包装器...

但是,每次我重新启动应用程序时,该值都会被清除。 (注意:我在SceneDelegate传递了数据)

视频示例:Click Here (真的很抱歉,视频质量是从我的手机上拍摄的)

ContentView:

import SwiftUI

struct ContentView: View {
    @EnvironmentObject private var userData: UserData
    var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        return formatter
    }

    var body: some View {
        NavigationView{
            VStack(){
                Text(dateFormatter.string(from: userData.licenseDate))
                NavigationLink(destination: SettingsView().environmentObject(self.userData)){
                    Text("Settings")
                }
            }
        }
    }
}

SettingsView:

import SwiftUI

struct SettingsView: View {
    @EnvironmentObject var userData: UserData
    
    var body: some View {
        HStack(){
            DatePicker(selection: $userData.licenseDate, in: ...Date(), displayedComponents: .date)
            {
                EmptyView()
            }
        }
    }
}

UserData:

import SwiftUI

final class UserData: ObservableObject  {
    @Published var licenseDate: Date = Date()
}

0 个答案:

没有答案