我定义了几个(最多)不同的SwiftUI视图:
ViewA(),ViewB(),ViewC().. ViewN()
每个视图都包含一个特定的信息,我想根据用户的选择来显示。
我创建了一个可哈希的,可标识的项目列表,我想将每个项目链接到一个特定的视图。但是我似乎无法克服这些错误。
这是我正在尝试做的一个具体示例:
//Country Definitions:
import Foundation
import Combine
import SwiftUI
let Countries = [
CountryModel(countryID: "US", countryName: "United States", countryView: USAView() )
CountryModel(countryID: "UK", countryName: "United Kingdom", countryView: UKView() )
]
struct CountryModel: Identifiable, Hashable {
let id:UUID
let countryID:String
let countryName:String
let countryView:View //I have tried AnyView here, different issues, still no go...
init(countryID:String, countryName:String, countryView:View) {
self.id = UUID();
self.countryID = countryID
self.countryName = countryName
self.countryView = countryView
}
}
计划如何在理论上使用它在NavigationView / NavigationLink中,如下所示:
struct ContentView: View {
var body: some View {
NavigationView {
ForEach(Countries) { thisCoutry in
NavigationLink(destination: thisCoutry.countryView) { //Also tried forcing as! View, no good
MyItemCell(itemName: thisCoutry.countryName, itemDesc: thisCoutry.countryID)
}
}
}
}
}
(MyItemCell只是一个用于格式化项目名称和ID的视图)。
到目前为止,尝试使用“视图”,我得到了以下错误:
协议“视图”只能用作一般约束,因为它具有“自身”或相关类型要求
还有一些关于不符合Equatable的问题。当我添加Equatable并使其具有返回true的存根时,没有帮助...
struct CountryModel: Hashable, Identifiable, Equatable {
static func == (lhs: CountryModel, rhs: CountryModel) -> Bool {
return true
}
我还收到一条错误消息,声称它不符合Hashable,因此我尝试将其取出来,但还是没有成功。
任何想法表示赞赏。由于SwiftUI似乎在大约10点左右/之后变得时髦,因此尝试避免导航链接的列表过长,因此我必须开始分组,或者要更有创意...
struct ContentView: View {
var body: some View {
VStack{
NavigationView {
NavigationLink(destination: ViewA()) {
MyItemCell(itemName: "United States", itemDesc: "USA")
}
NavigationLink(destination: ViewB()) {
MyItemCell(itemName: "United Kingdom", itemDesc: "UK")
}
}
}
}
}
您可以使用AnyView
类型擦除包装器(但它不仅应在模型中声明,还应在创建时显式使用-强制转换在这里不起作用,我认为这是错误的根源):
let Countries = [
CountryModel(countryID: "US", countryName: "United States",
countryView: AnyView(USAView()) ) // << here !!
CountryModel(countryID: "UK", countryName: "United Kingdom",
countryView: AnyView(UKView()) )
]
struct CountryModel: Identifiable, Hashable {
let id:UUID
let countryID:String
let countryName:String
let countryView:AnyView
init(countryID:String, countryName:String, countryView:View) {
self.id = UUID();
self.countryID = countryID
self.countryName = countryName
self.countryView = countryView
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句