这是一个非常奇怪的问题,因为我无法使用隔离的代码进行复制,但是我希望有人可以考虑一下原因。我有一个视图,假设ContentView的ContentViewModel是ObservedObject,然后还有另一个View ContentView2。而且我们在ContentView中有NavigationView,它将导航链接包装到ContentView2。这有点怪异,但是当我们进行一些会影响ContentViewModel的更改时,NavigationView会弹出ContentView2,以便最终显示在最初的ContentView中,但是我们并没有执行任何操作,例如关闭ContentView2或点击返回按钮。我有一个与我的项目中使用的代码相似的代码,但是请注意,在此代码中,所有功能都可以正常工作:
func qrealm() -> Realm {
return try! Realm(configuration: .init( inMemoryIdentifier: "yw"))
}
class SomeRObj: Object {
@objc dynamic var name: String = ""
convenience init(name: String) {
self.init()
self.name = name
}
static var instance: SomeRObj {
return qrealm().objects(SomeRObj.self).first!
}
}
struct SomeRObjWrapped: Hashable {
var obj: SomeRObj
var prop: Int
}
class ContentViewModel: ObservableObject {
@Published var someRObj: [SomeRObjWrapped] = []
var any: Any?
init() {
let token = qrealm().objects(SomeRObj.self).observe { changes in
switch changes {
case let .initial(data), let .update(data, deletions: _, insertions: _, modifications: _):
let someObjs = data.map { SomeRObjWrapped(obj: $0, prop: Int.random(in: 1..<50)) }
self.someRObj = Array(someObjs)
default: break
}
}
self.any = token
}
}
struct ContentView: View {
@ObservedObject var model: ContentViewModel = ContentViewModel()
var body: some View {
NavigationView {
VStack {
ForEach(model.someRObj, id: \.self) { obj in
Heh(obj: obj.obj, pr: obj.prop)
}
NavigationLink(destination: ContentView2()) {
Text("Link")
}
}
}
}
}
struct Heh: View {
var obj: SomeRObj
var pr: Int
var body: some View {
Text("\(obj.name) \(pr)")
}
}
struct ContentView2: View {
var body: some View {
Button(action: { try! qrealm().write {
let elem = qrealm().objects(SomeRObj.self).randomElement()
elem?.name = "jotaro kujo"
}
}, label: { Text("Toggle") })
}
}
最佳答案
您可以将\.self
替换为\.id
:
ForEach(model.someRObj, id: \.id) { obj in
Heh(obj: obj.obj, pr: obj.prop)
}
然后,每个对象都将由id
标识,并且ForEach
循环仅在id
更改时才会刷新。关于ios - SwiftUI NavigationView自行弹出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63385352/