I don't understand why the Text
updates but the List
does not.
I have a model with a @Published
which is an array of dates.
There's also a method to generate text from the dates.
Here's a simplified version:
class DataModel: NSObject, ObservableObject {
@Published var selectedDates: [Date] = []
func summary() -> String {
var lines: [String] = []
for date in selectedDates.sorted().reversed() {
let l = "\(someOtherStuff) \(date.dateFormatted)"
lines.append(l)
}
return lines.joined(separator: "\n")
}
}
And I show this text in my view. Here's a simplified version:
struct DataView: View {
@ObservedObject var model: DataModel
var body: some View {
ScrollView {
Text(model.summary())
}
}
}
It works: when the user, from the UI in the View, adds a date to model.selectedDates
, the summary text is properly udpated.
Now I want to replace the text with a List of lines.
I change the method:
func summary() -> [String] {
var lines: [String] = []
for date in selectedDates.sorted().reversed() {
let l = "\(someOtherStuff) \(date.dateFormatted)"
lines.append(l)
}
return lines
}
And change the view:
var body: some View {
ScrollView {
List {
ForEach(model.summary(), id: \.self) { line in
Text(line)
}
}
}
}
But this doesn't work: there's no text at all in the list, it is never updated when the user adds a date to model.selectedDates
.
What am I doing wrong?