如何解决SwiftUI选项卡选择不适用于任何可哈希内容
SwiftUI的“标签”选择应该可以与任何可散列的内容一起使用,但是似乎不起作用。
在提供的示例中,您可以看到在“工作”选项卡中,如果您使用整数作为选项卡选择,则显示正确运行。当您切换到“残破”标签时,所选内容是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)
}
}
}
解决方法
否,这不是SwiftUI错误。选择的类型和标记的类型必须相同,因此在第一种情况下它们都是整数,但在第二种情况下它们并不相同-选择是ColorItem
,但是标记仍然是整数-因此选择不起作用。
这是固定的变体:
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(items[i]) // << here !!
}
}
.tabViewStyle(PageTabViewStyle())
VStack{
Text(items.firstIndex(of: tabSelection)?.description ?? "N/A")
Text(tabSelection.title)
}
.font(.largeTitle)
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。