问题
How to have both a button in navigation bar and a list with sections?
Here is a code with .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()
}
}
}
}
Without .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()
}
}
}
}
Result with .navigationBarItems
:
Result without .navigationBarItems
:
回答1:
Just move those modifiers out of dynamic content, otherwise you try to include duplicated bar items for every section, that seems makes SwiftUI engine crazy.
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()
}
}
}
来源:https://stackoverflow.com/questions/63193141/list-sections-do-not-work-correctly-if-navigationbaritems-is-present