SwiftUI:当我解锁应用程序时,它会将我带回列表



我的应用程序有一些问题。当我在内容视图中锁定它,然后解锁它时,它会将我带回列表。我希望锁定前的视图在解锁后仍然可见。我曾试图以某种方式达到这种效果,但没有成功。请给我一个提示。

更重要的是,如果我点击心脏,项目被标记为最喜欢的,它也会将我移回列表。在这里,我也希望在选择了心之后继续留在视野中。如何消除此问题?

以下是使用苹果示例代码的示例用法,因为您没有提供任何实体信息

struct ContentView: View {
@Environment(.managedObjectContext) private var viewContext

@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: Item.timestamp, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
//SceneStorage to preserve the selected item by the user
@SceneStorage("ContentView.selection") var selection: String?
var body: some View {
NavigationView {
List {
ForEach(items) { item in
//Use the NavigationLink that uses selection
NavigationLink(tag: item.objectID.description, selection: $selection,
destination: {
//to edit/ observe the item pass it to an @ObservedObject
EditItemView2(item: item)
}, label: {
VStack{
Text(item.timestamp!, formatter: itemFormatter)
}

})
Button("delete", action: {
withAnimation(.easeOut(duration: 2)){
try? viewContext.delete(item)
}
})
}.onDelete(perform: deleteItems)
}

}
.toolbar {
#if os(iOS)
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
#endif
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
Text("Select an item")

}

private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error (nsError), (nsError.userInfo)")
}
}
}

private func deleteItems(offsets: IndexSet) {
withAnimation(.easeOut(duration: 2)) {
offsets.map { items[$0] }.forEach(viewContext.delete)

do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error (nsError), (nsError.userInfo)")
}
}
}
}
private let itemFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
return formatter
}()
struct EditItemView2: View{
//This observes the item and allows changes to the object
@ObservedObject var item: Item
var body: some View{
DatePicker("timestamp", selection: $item.timestamp.bound)
}
}

这个页面谈论了所有关于它的

https://developer.apple.com/documentation/uikit/view_controllers/restoring_your_app_s_state_with_swiftui

如果您的视图是第一个创建UserSettings对象的视图,我建议您使用@StateObject而不是@ObservedObject,尤其是当该对象是视图的唯一所有者并且没有被任何其他视图观察到时。

最新更新