我有一个 TabView,它具有嵌套在导航 View 和链接内的三个 View (三角形、正方形和圆形)。 TabView 工作正常。我想要仅用于特定选项卡 View 的工具栏按钮;说圆。工具栏修改器在所有选项卡 View 上添加按钮。
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink() {
TabView {
Text("triangle")
.tabItem {
Label("triangle", systemImage: "triangle")
}
Text("square")
.tabItem {
Label("square", systemImage: "square")
}
Text("circle")
.tabItem {
Label("circle", systemImage: "circle")
}
}
.navigationTitle("Tabs")
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
Button("About") {
print("About tapped!")
}
Button("Help") {
print("Help tapped!")
}
}
}
} label: {
Text("Hello!")
}
.navigationTitle("Title")
}
}
}
如何将其设置为仅在一个选项卡 View 上显示工具栏按钮?
我认为次要选项(不太优选)可能是禁用选项卡 View 上不需要的按钮(如果可能)。
最佳答案
可以通过 TabView
的选择状态来完成,并根据该状态使特定工具栏按钮可见。
这是一个演示。使用 Xcode 13.4/iOS 15.5 进行测试
struct ContentView: View {
@State private var selection = 0 // << here !!
var body: some View {
NavigationView {
NavigationLink() {
TabView(selection: $selection) { // << here !!
Text("triangle")
.tabItem {
Label("triangle", systemImage: "triangle")
}.tag(0)
Text("square")
.tabItem {
Label("square", systemImage: "square")
}.tag(1)
Text("circle")
.tabItem {
Label("circle", systemImage: "circle")
}.tag(2)
}
.navigationTitle("Tabs")
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
if selection == 2 { // << here !!
Button("About") {
print("About tapped!")
}
Button("Help") {
print("Help tapped!")
}
}
}
}
} label: {
Text("Hello!")
}
.navigationTitle("Title")
}
}
}
关于swiftui - 快速导航栏,在特定选项卡 View 项目上带有工具栏按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72586168/