I started playing with SwiftUI in the last few days and it makes a lot of sense. However, I'm struggling when it comes to updating a persisting list.
I'm using UserDefaults and JSONEncoder.
struct ContentView: View {
private var slackController = Slack()
@EnvironmentObject var userData: UserData
var body: some View {
return NavigationView {
List {
ForEach(self.userData.statuses) { myStatus in
HStack {
// row code
}
.onTapGesture {
self.slackController.setStatus(text: myStatus.description, emoji: myStatus.emoji)
}
}
.onDelete(perform: delete)
}
}
}
func delete(at offsets: IndexSet) {
self.userData.statuses.remove(atOffsets: offsets)
}
Both insert and delete are working, because when I relaunch the app I can see the changes.
private let defaultStatuses: [Status] = [
Status(emoji: ":spiral_calendar_pad:", description: "In a meeting", expireHours: 1),
Status(emoji: ":car:", description: "Commuting", expireHours: 12),
]
final class UserData: ObservableObject {
let didChange = PassthroughSubject<UserData, Never>()
@UserDefault(key: "ApiToken", defaultValue: "")
var apiToken: String {
didSet {
didChange.send(self)
}
}
@UserDefault(key: "Statuses", defaultValue: defaultStatuses)
var statuses: [Status] {
didSet {
didChange.send(self)
}
}
}
I can see that didChange.send(self)
is called, but I can't figure out why the list isn't updated.
The code is also in a repo in case I've missed something from the example that is useful. I've also been using SwiftUITodo to try figure out I'm doing wrong.
Any help/guideance would be appreciated.