[SUI] 侧边栏 (Sidebar)

发布: (2026年2月12日 GMT+8 00:24)
3 分钟阅读
原文: Dev.to

Source: Dev.to

描述

在 iPadOS 和 macOS 上,可以通过使用 tabViewStyle(_:)TabView 设置为 sidebarAdaptable,从而在侧边栏中呈现标签页。

sidebar 中,可以使用 TabSection 将标签页分组为不同的章节。如果有孤立的标签页,它们会显示在所有章节的上方。

可以使用 tabViewSidebarHeader(content:) 为侧边栏配置标题,使用 tabViewSidebarFooter(content:) 配置页脚。此外,还可以在侧边栏底部添加唯一的按钮,使用 tabViewSidebarBottomBar(content:)

当使用 TabContent.badge(_:) 时,数字会出现在标签页名称的右侧。

选中某个 Tab 时,侧边栏会关闭,标签页会在顶部栏中保持选中状态(相当于使用了 tabBarOnly)。如果该 Tab 位于 TabSection 中,相应的章节也会被选中。

在不同章节之间切换 Tab 时,每个章节都会保留上一次选择的 Tab 的状态。

示例代码

enum TabFeature {
    case home, remove, trips, account, send
}

struct ContentView: View {

    @State private var selectedTab = TabFeature.home
    @State private var newTrips = 2

    var body: some View {
        TabView(selection: $selectedTab) {
            TabSection("Sección con nombre largo 1") {
                Tab("Tab 1", systemImage: "house", value: TabFeature.home) {
                    Text("Contenido Tab 1")
                        .background(Color.blue.opacity(0.7))
                }
                Tab("Tab 2", systemImage: "trash", value: TabFeature.remove) {
                    Text("Contenido Tab 2")
                        .background(Color.red.opacity(0.7))
                }
            }
            TabSection("Sección 2") {
                Tab("Tab 3", systemImage: "airplane", value: TabFeature.trips) {
                    Text("Contenido Tab 3")
                        .background(Color.blue.opacity(0.7))
                        .onAppear {
                            newTrips = 0
                        }
                }
                .badge(newTrips)

                Tab("Tab 4", systemImage: "person", value: TabFeature.account) {
                    Text("Contenido Tab 4")
                        .background(Color.red.opacity(0.7))
                }
            }

            Tab("Tab 6", systemImage: "message", value: TabFeature.send) {
                Text("Contenido Tab 5")
                    .background(Color.red.opacity(0.7))
            }
        }
        .tabViewSidebarHeader {
            Label("Este es el header", systemImage: "gear")
        }
        .tabViewSidebarBottomBar {
            Button("Acción 1") {
                newTrips += 1
            }
            Button("Acción 2 NO VISIBLE") {
                print("Hago algo")
            }
        }
        .tabViewSidebarFooter {
            Label("Este es el footer", systemImage: "cloud")
        }
        .tabViewStyle(.sidebarAdaptable)
    }
}

图片

Sidebar example 1

Sidebar example 2

参考文献

0 浏览
Back to Blog

相关文章

阅读更多 »

你再也不能相信互联网了

markdown 这是一个 “byte” 帖子。它可能没有其他帖子那么详细。我喜欢奇怪且有点晦涩的事物。这是我的习惯,而且很多 t...