在 SwiftUI 中使用 TabView 时,如何才能显示选定的 Tab,如下图所示?
我尝试在每个选项卡中创建一个 VStack,如下所示:
struct ContentView: View {
@State public var tabViewSelection = 0
var body: some View {
TabView(selection: $tabViewSelection) {
HomeFirstLevel()
.tabItem {
VStack {
Image("HomeIcon")
Rectangle()
.frame(height: 7)
.foregroundColor((tabViewSelection == 0) ? .black : .clear)
}
}.tag(0)
}
}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用。我什至似乎无法添加矩形而不是图像:
HomeFirstLevel()
.tabItem {
Rectangle()
}.tag(0)
Run Code Online (Sandbox Code Playgroud)
TabView 不接受形状吗?先谢谢您的帮助!
您不能在 tabItem 中设置形状。但您可以使用ZStack在选项卡栏上添加形状并设置 x 位置。
这是演示。
struct ContentViewTabDemo: View {
@State public var tabViewSelection = 0
private var singleTabWidth = UIScreen.main.bounds.width / 5
var body: some View {
ZStack(alignment: .bottomLeading) {
TabView(selection: $tabViewSelection) {
Color.red
.tabItem {
VStack {
Image(systemName: "circle.fill")
}
}.tag(0)
Color.blue
.tabItem {
VStack {
Image(systemName: "heart.fill")
}
}.tag(1)
Color.red
.tabItem {
VStack {
Image(systemName: "circle.fill")
}
}.tag(2)
Color.blue
.tabItem {
VStack {
Image(systemName: "heart.fill")
}
}.tag(3)
Color.red
.tabItem {
VStack {
Image(systemName: "circle.fill")
}
}.tag(4)
}
Rectangle()
.offset(x: singleTabWidth * CGFloat(tabViewSelection))
.frame(width: singleTabWidth, height: 7)
.padding(.bottom, 2)
.animation(.default)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5901 次 |
| 最近记录: |