I’m experiencing an issue with duplicate toolbars in my application. The code seems to work, but it creates a double toolbar at the top of the modal for some reason. The following code creates a modal dialog for updating a list of locations:
import SwiftUI
import SwiftData
struct XMarkButton: View {
var body: some View {
Image(systemName: "xmark") //changed to image, can change color here if needed
.font(.headline)
}
}
struct SettingsView: View {
@Environment(.modelContext) private var modelContext
@Environment(.dismiss) private var dismiss
@Query private var locations: [Location]
@State private var showCreate = false
var body: some View {
NavigationSplitView {
List {
ForEach(locations) { location in
HStack {
Text(location.name)
.font(.largeTitle)
.bold()
}
}
.onDelete(perform: deleteLocations)
}
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
XMarkButton().onTapGesture { // on tap gesture calls dismissal
dismiss()
}
}
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
ToolbarItem {
Button(action: {
showCreate.toggle()
}, label: {
Label("Add Item", systemImage: "plus")
})
}
}
.sheet(isPresented: $showCreate,
content: {
NavigationStack {
CreateLocationView()
}
.presentationDetents([.large])
})
} detail: {
Text("Select a location")
}
}
private func addLocation() {
withAnimation {
let newLocation = Location()
modelContext.insert(newLocation)
}
}
private func deleteLocations(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(locations[index])
}
}
}
}
#Preview {
SettingsView()
}
Here is a screenshot so that you can see what I mean:
Could you provide guidance or suggestions on how to prevent or resolve this problem? Any advice would be greatly appreciated.
Eric A. Zarko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3