这听起来像是 if 的完美使用SceneStorage
"当你需要自动恢复值的状态时,你使用 SceneStorage。SceneStorage 的工作原理与 State 非常相似,只是它的初始值如果之前保存过,系统会恢复它的初始值,并且该值与同一场景中的其他 SceneStorage 变量共享。 ”
@SceneStorage("ContentView.selectedProduct") private var selectedProduct: String?
@SceneStorage("DetailView.selectedTab") private var selectedTab = Tabs.detail
它仅在 iOS 14+ 中可用,因此必须执行一些手动操作。也许在 CoreData 中有一些东西。每个重要状态变量都有变量的对象。它会像ObservedObject
ViewModel
持久性一样工作。
还。你可以试试...
“一个 NSUserActivity 对象捕获应用程序在当前时刻的状态。例如,包括有关应用程序当前显示的数据的信息。系统保存提供的对象并在下次启动时将其返回给应用程序。示例创建当用户关闭应用程序或应用程序进入后台时,一个新的 NSUserActivity 对象。”
下面是一些示例代码,总结了如何将它们组合在一起。这不是一个最小的可重现示例,因为它是来自 Apple的名为“ Restoring Your App's State with SwiftUI ”的更大项目的一部分。但它给出了如何实现它的一个很好的画面。
struct ContentView: View {
// The data model for storing all the products.
@EnvironmentObject var productsModel: ProductsModel
// Used for detecting when this scene is backgrounded and isn't currently visible.
@Environment(\.scenePhase) private var scenePhase
// The currently selected product, if any.
@SceneStorage("ContentView.selectedProduct") private var selectedProduct: String?
let columns = Array(repeating: GridItem(.adaptive(minimum: 94, maximum: 120)), count: 3)
var body: some View {
NavigationView {
ScrollView {
LazyVGrid(columns: columns) {
ForEach(productsModel.products) { product in
NavigationLink(destination: DetailView(product: product, selectedProductID: $selectedProduct),
tag: product.id.uuidString,
selection: $selectedProduct) {
StackItemView(itemName: product.name, imageName: product.imageName)
}
.padding(8)
.buttonStyle(PlainButtonStyle())
.onDrag {
/** Register the product user activity as part of the drag provider which
will create a new scene when dropped to the left or right of the iPad screen.
*/
let userActivity = NSUserActivity(activityType: DetailView.productUserActivityType)
let localizedString = NSLocalizedString("DroppedProductTitle", comment: "Activity title with product name")
userActivity.title = String(format: localizedString, product.name)
userActivity.targetContentIdentifier = product.id.uuidString
try? userActivity.setTypedPayload(product)
return NSItemProvider(object: userActivity)
}
}
}
.padding()
}
.navigationTitle("ProductsTitle")
}
.navigationViewStyle(StackNavigationViewStyle())
.onContinueUserActivity(DetailView.productUserActivityType) { userActivity in
if let product = try? userActivity.typedPayload(Product.self) {
selectedProduct = product.id.uuidString
}
}
.onChange(of: scenePhase) { newScenePhase in
if newScenePhase == .background {
// Make sure to save any unsaved changes to the products model.
productsModel.save()
}
}
}
}