Hello dear swiftui learners;-)
I have been trying to create a simple workout application, hovever it seems I have skipped some basics and can't make my views update on property change
here is my code:
import SwiftUI
@main
struct TestAppApp: App {
@StateObject var manager = HealthKitManager()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(manager)
}
}
}
struct ContentView: View {
@EnvironmentObject var manager: HealthKitManager
var body: some View {
ScrollView {
ForEach(manager.activities.sorted(by: {$0.value.id < $1.value.id}), id: \.key) { item in
ActivityCard(activity: item.value)
}
}
.refreshable {
manager.update()
}
}
}
struct Activity: Identifiable {
var id: Int
var title: String
var amount: Int
}
struct ActivityCard: View {
@State var activity: Activity
var body: some View {
VStack {
Text(activity.title)
Text("\(activity.amount)")
}
}
}
class HealthKitManager: ObservableObject {
@Published var activities: [String : Activity] = [
"steps": Activity(id: 1, title: "Steps", amount: 0),
"calories": Activity(id: 2, title: "Calories", amount: 0)
]
func update() {
let activity = Activity(id: 3, title: "Distance", amount: 10)
self.activities["distance"] = activity // this work
self.activities["steps"]?.amount = 10 // this does not!
print(self.activities) // but it's updated
}
}
if I add new activity to activities it will work, but if i try to update property of existing activity it's no luck.
chatgpt suggested to change struct to class - not working
class Activity: Identifiable, ObservableObject {
var id: Int
var title: String
@Published var amount: Int
init(id: Int, title: String, amount: Int) {
self.id = id
self.title = title
self.amount = amount
}
}
another suggestion was objectWillChange.send() - not working
objectWillChange.send()
self.activities["steps"]?.amount = 10
objectWillChange.send()
I have been trying everything, can somebody please help me?
thank you!
Peter