Skip to content

SwiftUI组件-TabView (ing)

https://developer.apple.com/documentation/swiftui/tabview
https://developer.apple.com/documentation/swiftui/tabviewstyle

基本用法

使用TabView + tabItem 实现tabbarController的效果。

  • tabItem内容支持Label以及 Image/Text的组合
  • tabItem支持显示badge
  • TabView默认样式支持一页支持五个tabItem,手机超过五个显示“More”,ipad上会显示更多。
swift
struct TabViewsBasic: View {
    var body: some View {
        TabView {
            Text("Page1")
                .tabItem {
                    // tabItem 内容支持 Label
                    Label("Story", systemImage: "book")
                }
                .badge(2)
            
            Text("Page2")
                .tabItem {
                    // tabItem 内容支持 Image/Text 组合
                    Image(systemName: "person")
                    Text("Page1")
                }
                .badge("!")

            Text("Page3")
                .tabItem {
                    Label("Lightning", systemImage: "bolt.fill")
                }
    }
}
struct TabViewsBasic: View {
    var body: some View {
        TabView {
            Text("Page1")
                .tabItem {
                    // tabItem 内容支持 Label
                    Label("Story", systemImage: "book")
                }
                .badge(2)
            
            Text("Page2")
                .tabItem {
                    // tabItem 内容支持 Image/Text 组合
                    Image(systemName: "person")
                    Text("Page1")
                }
                .badge("!")

            Text("Page3")
                .tabItem {
                    Label("Lightning", systemImage: "bolt.fill")
                }
    }
}

|300

TabView selection

TabView支持默认选中某一项,例如进入页面,显示第二个tabItem的内容。使用

swift
/**
 使用 TabView(selection: ...) 结合 `tag` 实现选中哪个页面的效果。 满足hashable即可,可以用枚举让其更优雅
 */
struct TableViewWithIndex: View {
    @State var selectIndex: Int = 1
    var body: some View {
        TabView(selection: $selectIndex) {
            Text("Page1")
                .tabItem {
                    Image(systemName: "person")
                    Text("Page1")
                }.tag(0)
            
            Text("Page2")
                .tabItem {
                    Label("Story", systemImage: "book")
                }.tag(1)
        }
    }
}
/**
 使用 TabView(selection: ...) 结合 `tag` 实现选中哪个页面的效果。 满足hashable即可,可以用枚举让其更优雅
 */
struct TableViewWithIndex: View {
    @State var selectIndex: Int = 1
    var body: some View {
        TabView(selection: $selectIndex) {
            Text("Page1")
                .tabItem {
                    Image(systemName: "person")
                    Text("Page1")
                }.tag(0)
            
            Text("Page2")
                .tabItem {
                    Label("Story", systemImage: "book")
                }.tag(1)
        }
    }
}

TabViewStyle

  • 默认样式:类似UIKit中的tabbarController
  • tabViewStyle 效果类似UIKit中的pageViewController