英文:
How to remove toolbar ToolBarItem() from a view (SwiftUI)
问题
将 ToolBarItem 添加到我的顶部导航栏并在通过底部的选项卡导航到另一个视图时,前一个视图的 ToolBarItem 仍然可见。是否可以重置第二个视图的 ToolBarItems 或导航工具栏?
在 ContentView() 中,我有以下代码:
TabView(selection: $selectedTab) {
Home()
.tabItem {
Label("主页", systemImage: "house")
.foregroundColor(.primary)
}
.tag("主页")
Other()
.tabItem {
Label("其他", systemImage: "heart")
.foregroundColor(.primary)
}
.tag("其他")
}
在 Home() 视图内部,我有以下代码:
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Image(systemName: "gearshape")
}
}
当我导航到 Other() 时,仍然会显示来自 Home() 的工具栏。
英文:
When adding ToolBarItem's to my top navigation bar and I navigate to another view (via a tabbar at the bottom) - the ToolBarItem's from the previous view are still visible. Is it possible to reset the ToolBarItems or Navigation Toolbar for the 2nd view?
ContentView() I have
TabView(selection: $selectedTab) {
Home()
.tabItem {
Label("Home", systemImage: "house")
.foregroundColor(.primary)
}
.tag("Home")
Other()
.tabItem {
Label("Other", systemImage: "heart)
.foregroundColor(.primary)
}
.tag("Other")
}
Inside Home() I have
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Image(systemName: "gearshape")
}
}
When I navigate to Other() the toolbar from Home() is still shown.
答案1
得分: 1
在 HomeView 中,您应该添加一个 NavigationView 或 NavigationStack,并将您的代码修改如下以实现所需的效果:
struct Home: View {
var body: some View {
NavigationView {
//您的视图在此
}
}
}
不同之处在于:
NavigationView为其子视图提供了导航栏。当您将视图嵌套在 NavigationView 中时,您将启用导航栏和工具栏项目的显示。- 如果您不使用
NavigationView,但仍然在HomeView中使用toolbar,这意味着带有齿轮图标的工具栏项目将直接添加到TabView中。这样一来,工具栏项目将在所有选项卡中始终显示一致。
英文:
Inside the HomeView you should add a NavigationView or NavigationStack and modifier your code as follows to achieve the desired effect:
struct Home: View {
var body: some View {
NavigationView {
//Your view here
}
}
}
What is different:
NavigationViewprovides a navigation bar for its child views. When you embed your view inside a NavigationView, you're enabling the display of the navigation bar and toolbar items.- If you don't use the
NavigationViewand still have thetoolbarin theHomeView. That means the toolbar item with the gear icon is added directly to theTabView. This way, the toolbar item will be displayed consistently across all tabs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论