这听起来像是 if SceneStorage 的完美使用
“You use SceneStorage when you need automatic state restoration of the value. SceneStorage works very similar to State, except its initial value is restored by the system if it was previously saved, and the value is· shared with other SceneStorage variables in the same scene.”
@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()
}
}
}
}