我已将一个工具栏添加到导航路径的根视图中,当我转到路径中的下一个屏幕时,它会消失。
我尝试将其作为导航堆栈的修改器,但随后它完全消失了。
如何做到这一点,以便在导航到详细信息屏幕后,工具栏仍然在视图中显示我的购物车工具栏项目?
我创建了一个导航堆栈,如下所示:
var body: some View {
NavigationStack(path: $navigation.navigationPath) {
LandingScreen()
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
// TODO: Add action here
}) {
Image(systemName: "cart")
}
}
ToolbarItem(placement: .principal) {
Text("Store") // Locally I add a custom font to this which is why it is done this way.
}
}
.navigationDestination(for: Item.self) { item in
DetailScreen(item: item)
}
}
}
这是我的登陆屏幕:
struct LandingScreen: View {
@EnvironmentObject var navigation: NavigationManager
/// Temporary data for this screen until it is setup
let items = [Item(name: "Item 1"),
Item(name: "Item 2"),
Item(name: "Item 3"),
Item(name: "Item 4"),
Item(name: "Item 5"),
Item(name: "Item 6"),
Item(name: "Item 7"),
Item(name: "Item 8"),
Item(name: "Item 9"),
Item(name: "Item 10"),
Item(name: "Item 11"),
Item(name: "Item 12")]
var body: some View {
ScrollView(showsIndicators: false) {
LazyVStack {
ForEach(items, id: \.self) { item in
Button(action: {
navigation.navigationPath.append(item)
}, label: {
Text("Item Button")
})
}
}
}
.padding([.leading, .trailing])
}
}
这是我的详细信息屏幕:
struct DetailScreen: View {
let item: Item
var body: some View {
Text("Detail Screen for \(item.name)")
}
}
创建一个视图扩展函数,将工具栏添加到任何视图:
extension View {
func storeToolbar() -> some View {
self
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
// TODO: Add action here
}) {
Image(systemName: "cart")
}
}
ToolbarItem(placement: .principal) {
Text("Store")
}
}
}
}
然后只需将
.storeToolbar()
添加到您想要显示该工具栏的任何视图即可:
LandingScreen()
.storeToolbar()