我的目标是制作一个SwiftUI结构,该结构按顺序显示数据的滚动视图,其中数据和data_view放到ScrollView中。
我从ForEach行的此代码中获得标题错误。数组的类型似乎无关紧要,我将其设置为“ Any”,并得到相同的错误。
import SwiftUI
protocol DatedOrPrioritizedStruct {
var id: UUID {get}
var priority: Float {get set} ///Priority must be set
var start: Date? {get set} ///Could be nil. Used in conjunction with priority if set.
}
struct TimeLine : View {
var data: [DatedOrPrioritizedStruct]
var body: some View {
GeometryReader { geometry in
NavigationView {
VStack {
ScrollView {
ForEach(self.data, id: \.self) { item in
//^-ERROR redline here
TaskView(task: item).frame(minWidth: 0, idealWidth: geometry.size.width * 0.80, maxWidth: geometry.size.width, alignment: .leading)
}
}.frame(minWidth: 0, maxWidth: geometry.size.width, alignment: .leading)
.navigationBarTitle("Do The First Thing", displayMode: .large)
}
}.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
}
}
}
任务类:
public class Task: DatedOrPrioritizedStruct, Identifiable, Equatable {
public static func == (lhs: Task, rhs: Task) -> Bool {
return lhs.id == rhs.id
}
public let id = UUID()
var title: String
var creation: Date
var priority: Float
var start: Date?
var deadline: Date?
var completed: Date?
var note: String?
var recur: Double?
var duration: TimeInterval
public init (_ title: String) {
self.title = title
self.creation = Date()
self.priority = 3.0
self.start = nil
self.deadline = nil
self.completed = nil
self.note = nil
self.recur = nil
self.duration = 3600.0
}
public init (_ title: String, priority: Float) {
self.title = title
self.creation = Date()
self.priority = priority
self.start = nil
self.deadline = nil
self.completed = nil
self.note = nil
self.recur = nil
self.duration = TimeInterval(9 * 24 * 3600 + 3 * 3600 + 20 * 60)
}
}
答案 0 :(得分:0)
如果您更换
TaskView(task: item).frame(minWidth: 0, idealWidth: geometry.size.width * 0.80, maxWidth: geometry.size.width, alignment: .leading)
以简单的Text("Testing")
行,您会看到错误更改为
协议类型'DatedOrPrioritizedStruct'不能符合'Hashable',因为只有具体类型可以符合协议
您可以通过将ForEach
的标识符指定为\.id
来解决此问题:
ForEach(self.data, id: \.id) { item in
TaskView(task: item).frame(minWidth: 0, idealWidth: geometry.size.width * 0.80, maxWidth: geometry.size.width, alignment: .leading)
}
请确保TaskView
的{{1}}的类型为task
,而不是DatedOrPrioritizedStruct
,因为由于您的Task
数组包含data
个对象,则DataOrPrioritizedStruct
中的item
将是ForEach
,而不是DataOrPrioritizedStruct
。
附带说明:目前,Xcode经常会出现不相关的错误,例如在这种情况下,您可以尝试通过简化代码来找出真正的来源(我将{{1} },在Task
中注释掉)。
修改:
为了明确起见,Text("Testing")
期望接收ForEach
类型,但是TaskView
迭代TaskView
的数组,因此当您将Task
传递到{{1} }无法保证对象具有ForEach
唯一的数据成员,这就是DataOrPrioritizedStruct
的{{1}}类型必须为item
而不是{ {1}}。