StatefulTabView

一个 SwiftUI UITabBarController 实现,可在标签页切换时保留状态。 非常感谢 Amzd 以及所有帮助完善这个 gist 的人,因为它是设置此项目的主要起点。

要求

安装

Swift Package Manager

在 Xcode 11 或更高版本中,导航到 File > Swift Packages > Add Package Dependency...。 在那里只需添加 https://github.com/NicholasBellucci/StatefulTabView 作为软件包存储库 URL,并使用 master 分支或最新版本。 Master 将始终与最新版本保持一致。

目录

功能

用法

设置 StatefulTabView 相对简单,并且类似于原生的 TabView。 主要区别在于,选项卡的内容被包装在 Tab 结构体中。 可以使用的选项卡数量没有限制。 一旦使用超过 5 个,Apple 标准的“更多”选项卡将变为可用。 请随时查看示例项目以了解确切用法。

基础

StatefulTabView {
    Tab(title: "Tab 1", systemImageName: "circle.fill") {
        NavigationView {
            List {
                Section {
                    ForEach(0..<20, id: \.self) { index in
                        NavigationLink(destination: PushedView(text: "Pushed number \(index)")) {
                            Text("\(index)")
                        }
                    }
                }
            }
            .navigationBarTitle("Navigation View 1")
        }
    }
}

外观修改

所有外观修改都可以通过使用 StatefulTabView 的扩展来实现。

StatefulTabView {
    ...
}
.barTintColor(.red)
.unselectedItemTintColor(.green)
.barBackgroundColor(.yellow)
.barAppearanceConfiguration(.transparent)

选定的索引

StatefulTabView 的选中索引可以在初始化程序中设置。 传递的值是一个绑定。

@State var selectedIndex: Int = 2

StatefulTabView(selectedIndex: $selectedIndex) {
    ...
}

徽章值

TabBarItem 徽章值可以在 Tab 的初始化程序中设置。

@State var badgeValue: String = "1"

Tab(title: "Tab 1", systemImageName: "circle.fill", badgeValue: badgeValue) {
    ...
}

滚动到顶部(带大标题)

当选择已选择的选项卡时,包含在层次结构中的 scrollView 会处理滚动到顶部。 唯一的问题是,当调用 scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true) 时,导航栏中的大标题不会被考虑在内,这是显而易见的。 由于此限制,将 .prefersLargeTitle(true) 添加到 Tab 将解决此问题。 对于不使用大标题的根导航视图,无需更改 Tab

Tab(title: "Tab 1", systemImageName: "circle.fill") {
    NavigationView {
        List {
            ...
        }
        .navigationBarTitle("Navigation View 1", displayMode: .large)
    }
}
.prefersLargeTitle(true)

许可证

StatefulTabView 是并且永远是 MIT 许可。 有关详细信息,请参见 LICENSE