|
I'm learning the MVVM structure, but I just can't figure out a proper implementation for the User Settings (i.e. I wrote this very basic example. It works, but ContentView does not get refreshed to reflect the new value. I have to restart the app manually. What am I doing wrong ? Thanks !
|
|
|
|
This is what I thought. :-/ Is there any way to force ContentView to refresh when a Settings is updated? I am not too good with the Combine framework, but I suspect the solution is there. |
|
hi, if you are changing a user default within your view model, just execute if you are changing a user default outside your view model and outside its associated view (maybe you are changing a user default in another view, perhaps in another tab, and your view model needs to know about that change), i have used this idea. use
your view model can then listen for such a notification and respond by executing so, in your VM, you'd need three things:
hope that helps, DMG |
|
Just use a So something like this:
|
|
Wow I did not know about this, thank you very much for the tip ! -
I just came across this solution earlier, and while I think this is the best approach to this whole problem, it results in a lot of boilerplate code. It's not a problem per se, but I just wished a (custom?) property wrapper would do all of this. |
|
It's certainly possible to make a custom property wrapper to do just this. Wrapping |
|
I've seen plenty of custom property wrappers that simplified UserDefaults interactions, but none of them would work in a class in such a way that it would publish the new value to the view struct. It's basically the same problem as @AppStorage. Basically you cannot use objectWillChange.send() in property wrappers. I've worked my mind to combine both of your solutions @delawaremathguy and @rooserboy, and found a way to remove the init() and standardize the code in didSet to reduce error risks. It still has some boilerplate though. It works even when other views are impacted.
|
BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.
Sponsor Hacking with Swift and reach the world's largest Swift community!
This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.