This is my simple View:
struct Element: Identifiable {
let id = UUID()
let text: String
init(text: String) {
self.text = text
}
}
struct ServicesView: View {
@FetchRequest(sortDescriptors: [SortDescriptor(\.date, order: .reverse)], animation: .easeIn)
private var results: FetchedResults<Month>
var elements = [Element(text: "a"), Element(text: "b")]
var body: some View {
NavigationView {
List(elements) { element in
NavigationLink {
YearView(months: [])
} label: {
Text("abc")
}
}
.navigationTitle("Service")
}
}
}
This way the app is not working correctly, because it pops up my View (YearView
) from NavigationView
when app goes to inactive mode and YearView is already presented.
But, when I change to:
@State var elements = [Element(text: "a"), Element(text: "b")]
it works VERY correctly. I don't know why it makes a difference, but OK. I understand WHAT is wrong.
Unfortunately I need elements
as computed property... and as a @State
(for above issue). But @State
cannot be used for computed properties. How can I resolve it?
My Element here (Group in production code) is created base on fetched Months.
This is my real code:
struct Group: Identifiable { //Element in above example
let months: [Month]
var id = UUID()
var descriptiveYear: String {
months.first?.descriptiveYear ?? ""
}
init(months: [Month]) {
self.months = months
}
}
private var elements: [Group] {
var groups = [[Month]]()
var months = [Month]()
results.forEach { month in
guard months.isEmpty else {
if month.currentYear == months.first?.currentYear {
months.append(month)
} else {
groups.append(months)
months = [month]
}
return
}
months.append(month)
}
return groups.map { Group(months: $0) }
}