如果存在 .navigationBarItems,则列表部分无法正常工作

List Sections do not work correctly if .navigationBarItems is present

如何在导航栏中同时拥有按钮和包含部分的列表?

这是一个代码 .navigationBarItems:

struct AllMatchesView: View {
    @Environment(\.managedObjectContext) var moc
    
    @State var events = EventData()
    
    var body: some View {
        NavigationView {
            List{
                ForEach(events.sections) { section in
                    Section(header: Text(section.title)) {
                        ForEach(section.matches) { match in
                            Text("Row")
                        }
                    }
                        .navigationBarTitle("Title")
                        .navigationBarItems(trailing:
                            NavigationLink(destination: AddMatchView().environment(\.managedObjectContext, self.moc)) {
                                Image(systemName: "plus")
                                    .resizable()
                                    .frame(width: 22, height: 22)
                                    .padding(.horizontal)
                            }
                            .padding(.leading)
                    )
                }
            }.onAppear(){
                self.events = EventData()
            }
        }
    }
}

没有.navigationBarItems:

struct AllMatchesView: View {
    @Environment(\.managedObjectContext) var moc
    
    @State var events = EventData()
    
    var body: some View {
        NavigationView {
            List{
                ForEach(events.sections) { section in
                    Section(header: Text(section.title)) {
                        ForEach(section.matches) { match in
                            Text("Row")
                        }
                    }
                        .navigationBarTitle("Title")
                }
            }.onAppear(){
                self.events = EventData()
            }
        }
    }
}

结果 .navigationBarItems

没有.navigationBarItems的结果:

只需将这些修饰符移出动态内容,否则您会尝试为每个部分包含重复的条形项,这似乎会让 SwiftUI 引擎发疯。

    var body: some View {
        NavigationView {
            List{
                ForEach(events.sections) { section in
                    Section(header: Text(section.title)) {
                        ForEach(section.matches) { match in
                            Text("Row")
                        }
                    }
                }
            }
            .navigationBarTitle("Title")
            .navigationBarItems(trailing:
                NavigationLink(destination: AddMatchView().environment(\.managedObjectContext, self.moc)) {
                    Image(systemName: "plus")
                        .resizable()
                        .frame(width: 22, height: 22)
                        .padding(.horizontal)
                }
                .padding(.leading)
            )
            .onAppear(){
                self.events = EventData()
            }
        }
    }