【发布时间】:2021-02-16 05:19:36
【问题描述】:
SwiftUI 的选项卡选择应该适用于任何可散列的内容,但这似乎不起作用。
在提供的示例中,您可以看到在“工作”选项卡中,如果您使用整数进行选项卡选择,则一切都可以正常工作。当您切换到“Broken”选项卡时,选择是 ColorItem,并且选择不会更新视图。
我认为这是一个 SwiftUI 错误并已提交反馈 (FB8879981)。
使用 Xcode 12.2 和 iOS 14.2(RC) 测试。
struct ColorItem: Identifiable, Hashable{
let color: Color
let title: String
var id: String{
title
}
}
struct ContentView: View {
let items = [
ColorItem(color: .red, title: "Red"),
ColorItem(color: .blue, title: "Blue"),
ColorItem(color: .purple, title: "Purple")
]
var body: some View {
TabView{
TabViewWorking(items: items)
.tabItem {
Label("Working", systemImage: "hand.thumbsup")
}
TabViewBroken(items: items)
.tabItem {
Label("Broken", systemImage: "hand.thumbsdown")
}
}
}
}
struct TabViewWorking: View {
@State private var tabSelection = 0
let items: [ColorItem]
var body: some View {
ZStack{
TabView(selection: $tabSelection){
ForEach(0..<items.count){ i in
items[i].color.edgesIgnoringSafeArea(.all)
.tag(i)
}
}
.tabViewStyle(PageTabViewStyle())
VStack{
Text(tabSelection.description)
Text(items[tabSelection].title)
}
.font(.largeTitle)
}
}
}
struct TabViewBroken: View {
@State private var tabSelection = ColorItem(color: .red, title: "Red")
let items: [ColorItem]
var body: some View {
ZStack{
TabView(selection: $tabSelection){
ForEach(0..<items.count){ i in
items[i].color.edgesIgnoringSafeArea(.all)
.tag(i)
}
}
.tabViewStyle(PageTabViewStyle())
VStack{
Text(items.firstIndex(of: tabSelection)?.description ?? "N/A")
Text(tabSelection.title)
}
.font(.largeTitle)
}
}
}
【问题讨论】: