我考虑是否有可能在 SwiftUI 中向 TabView 添加更多 View ,然后再为 TabItems 留出空间。
我做了这样的事情:
TabView(selection: $selectedTab) {
Text("Hello World 1")
.tabItem {
Image(systemName: "1.circle")
Text("Item 1")
}.tag(0)
Text("Hello World 2")
.tabItem {
Image(systemName: "2.circle")
Text("Item 2")
}.tag(1)
Text("Hello World 3")
.tabItem {
Image(systemName: "3.circle")
Text("Item 3")
}.tag(2)
Text("Hello World 4")
.tabItem {
Image(systemName: "4.circle")
Text("Item 4")
}.tag(3)
Text("Hello World 5")
.tabItem {
Image(systemName: "5.circle")
Text("")
}.tag(4)
Text("Hello World 5")
.tabItem {
Image(systemName: "6.circle")
Text("")
}.tag(5)
}
并且会自动显示更多三点按钮。但我不想在选项卡栏中仅显示前 4 或 5 个项目,而其他项目将仅以编程方式导航。我想通过这种方式添加汉堡菜单,其中包含将切换其他 View 的按钮。
我知道汉堡/抽屉导航/侧面菜单不是苹果推荐的,但这样的设计非常适合我的应用程序要求。 :)
最佳答案
我希望以下方法有用。这个想法是具有动态范围,根据当前选择的选项卡项目显示选项卡项目。
对于此演示选择,包括可见选项卡,根据预览/下一步按钮进行更改,但这并不重要 - 选择的范围可能不同,它只需要根据所选选项卡更新可见选项卡的范围。就是这样。
以下是演示的行为方式:
struct ContentView: View {
static let maxTabs = 8
@State var selectedTab = 2
@State var visibleTabs = [0, 1, 2, 3]
var body: some View {
VStack {
self.selectorView
Divider()
TabView(selection: $selectedTab) {
ForEach(visibleTabs, id: \.self) { i in
self.viewForTab(i)
.tabItem {
Image(systemName: "\(i).circle")
Text("Item \(i)")
}.tag(i)
}
}
}
}
var selectorView: some View {
HStack {
Button(action: {
let prev = self.selectedTab - 1
if prev >= 0 {
if prev < self.visibleTabs.min()! {
self.visibleTabs = self.visibleTabs.map { $0 - 1 }
}
self.selectedTab = prev
}
}) {
Text("< Prev").padding([.top, .horizontal])
}.disabled(self.selectedTab == 0)
Button(action: {
let next = self.selectedTab + 1
if next < Self.maxTabs {
if next > self.visibleTabs.max()! {
self.visibleTabs = self.visibleTabs.map { $0 + 1 }
}
self.selectedTab = next
}
}) {
Text("Next >").padding([.top, .horizontal])
}.disabled(self.selectedTab == Self.maxTabs - 1)
}
}
private func viewForTab(_ tag: Int) -> some View {
// Provide your view for requested tab tag
Text("Hello World \(tag)")
}
}
关于SwiftUI:我可以向 TabView 添加更多 View ,然后添加选项卡项吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58981871/