gpt4 book ai didi

ios - 如何在 SwiftUI 中将 View() 作为列表的一部分传递?

转载 作者:行者123 更新时间:2023-12-04 03:46:52 24 4
gpt4 key购买 nike

我已经定义了一些(最多很多)不同的 SwiftUI View :

ViewA()、ViewB()、ViewC() ..ViewN()

每个 View 都包含我要根据用户所做的选择呈现的特定信息..

我创建了一个可散列的、可识别的项目列表,我想将每个项目链接到一个特定的 View 。但我似乎无法克服这些错误..

这是我正在尝试做的具体示例:

//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 的 View )..

到目前为止,尝试使用“查看”时,出现错误:

Protocol 'View' can only be used as a generic constraint because ithas Self or associated type requirements

还有一些关于不符合 Equatable 的内容。当我添加 Equatable 并让它添加返回 true 的 stub 时,没有帮助...

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
}
}

关于ios - 如何在 SwiftUI 中将 View() 作为列表的一部分传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65015283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com