【问题标题】:SwiftUI Navigation automatically closing/pop - RealmSwiftUI Navigation 自动关闭/弹出 - Realm
【发布时间】:2020-02-11 01:40:00
【问题描述】:

我正在使用领域结果集填充列表。

从该列表导航时,它会打开一个新视图,然后自动关闭该视图。

使用结构没有问题。

为什么第二个视图会自动关闭?

我有一个屏幕录像,但不能在这里发帖。

import SwiftUI
import Combine

struct TestStruct:Identifiable{

    let id = UUID()
    let firstname: String
}

extension TestStruct {
    static func all() -> [TestStruct]{
        return[
            TestStruct(firstname: "Joe"),
            TestStruct(firstname: "Jane"),
            TestStruct(firstname: "Johns")
        ]
    }
}

struct TestListView: View {
    let realmList = Horoscope.getHoroscopes() //Fetches from Realm
    let structList = TestStruct.all()

    var body: some View {
        NavigationView{
            // This owrks
            //            List(structList) { item in
            //                MyItemRow(itemTxt: item.firstname)
            //            }

            //This automatically closes the view
            List(realmList) { item in
                MyItemRow(itemTxt: item.firstname)
            }
            .navigationBarTitle("Charts", displayMode: .automatic)
            .navigationBarItems(trailing: EditButton())
        }
    }
}


struct MyItemRow: View {

    var itemTxt:String

    var body: some View {
        NavigationLink(destination: Text("Test")) {
            Text(itemTxt)
        }
    }
}

struct TestListView_Previews: PreviewProvider {
    static var previews: some View {
        TestListView()
    }
}

【问题讨论】:

  • 这里几乎没有错误检查,所以 item.firstname 可能为 nil,realmList 可能为空。另外,我认为 NavigationLink 需要嵌入到 NavigationView 中。
  • TestStruct.firstname 不能为零,它不是可选的。空列表适用于 ListForEachNavigationLinkMyItemRow 内,它嵌入在 NavigationView 中的 TestListView 中。
  • 好点。我更多地指的是let realmList = Horoscope.getHoroscopes(),但你指出的其他一切都是正确的。

标签: realm swiftui navigationlink


【解决方案1】:

我觉得可以在here找到答案

简而言之,不要生成ForEach 迭代的集合的id。它会检测到变化并返回。

Realm 对象的每个引用都有一个自动生成的id 属性,请尝试将其替换为一致的id

【讨论】:

  • 如果任何观察到的对象在 swiftUI 中发生变化,View 的构造函数会再次运行(至少在逻辑上),这意味着所有计算属性都会再次生成,从而导致数组具有不同的id- s。苹果教程中不会发生此类事件,因为它们非常简单。如果您在列表中有一个Realm 对象并且您更改(在写入块中修改)一个对象,并且您已准备好进行更改,因此您的objectWillChange-被调用,如果您使用ForEachIdentifiable Elements 构造函数。另外,请查看我链接的问题。
  • ps.:ForEachList 的行为与 Identifiable 集合类似。我提到了ForEach 这个问题提到了List
  • @gujci - 谢谢! - List 或 ForEach 会带来同样的问题。在基于 Ream 的对象中添加一个 getter 解决了这个问题。 var id: UUID {get { return UUID(uuidString: horoscopeId)!} }
  • 嗨@Yarm,我像你一样在我的id var中添加了一个getter,但问题仍然存在。你还做了什么?
猜你喜欢
  • 1970-01-01
  • 2021-08-13
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 2018-02-13
  • 2013-01-09
  • 1970-01-01
相关资源
最近更新 更多