我的应用程序中遇到重复工具栏的问题。该代码似乎有效,但由于某种原因它在模式顶部创建了一个双工具栏。以下代码创建一个用于更新位置列表的模式对话框:
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()
}
这是一个屏幕截图,以便您可以明白我的意思:
您有 2 个导航栏,因为您以某种方式嵌套导航
NavigationSplitView
NavigationStack
是一个常见的例子