How to bind a picker to a computed value SwiftUI - ios

I have a view SettingsView written using swiftui, and a data store SettingsStore that uses UserDefaults as the underlying data storage.
final class SettingsStore: ObservableObject {
var velocityLocation: RenderLocation {
set { defaults.set(newValue.rawValue, forKey: Keys.velocityLoaction) }
get { RenderLocation(rawValue: defaults.integer(forKey: Keys.velocityLoaction)) ?? .top }
}
}
struct SettingsView: View {
#State var settings: SettingsStore = SettingsStore();
var body: some View {
Form {
Section(header: Text("Render settings")) {
Toggle("Render velocity to video", isOn: $settings.renderVelocityToVideo)
Picker(selection: $settings.velocityLocation, label: Text("Render location")) {
ForEach(RenderLocation.allCases) { b in
Text(b.name).tag(b)
}
}
}
}
.navigationTitle("Settings")
}
}
When I pick a new value in the picker it is persisted to user defaults correctly, but it is not rendered to the view. This is because the get for the computed property is never called. If I leave that view and come back the picker now has the correct value.
I know my use of an Enum in the picker works as when I change the computed property in SettingsStore, to a simple #State property in the view everything works as expected (except of course saving to UserDefaults)
Is there a way to get computed property to render after being set or is there a better way to structure this code so that i can persist picker values easily.
(Yes I have tried this with other data types eg ints, string same issue)

Related

SwiftUI list item not updated if model is wrapped in #State

Given
a View with a simple List
an ItemView for each element of the list
a Model for the app
a model value (Deck)
Tapping on a button in the main view, is expected the model to change and propagate the changes to the ItemView.
The problem is that the changes only propagate if the model struct is stored in the ItemView as a normal variable; but if i add the #State property wrapper these do not happen. The view will update but not change (like if the data has been cached).
Question 1: is this an expected behaviour? If so, why? I was expecting to have the ItemView to only update when the model change by observing it throw #State, this way instead the view will always refresh whenever the list commands it, even if the data is not updated?
Question 2: Is it normal otherwise to have the items of a list using plain structs properties as models? Using observable classes would create much more complexity when handling the array in the view model and also make more complicated the List refreshing/identifying mechanism seems to me.
In the example the model does not need the #State, since changes are only coming from outside, in real world i would need it when it's the view itself to trigger the changes?
This is a stripped down version to reproduce the issue (create a project and replace ContentView with following):
import SwiftUI
struct Deck: Identifiable {
let id: Int
var name: String
init(_ name: String, _ id: Int) {
self.name = name
self.id = id
}
}
struct ItemView: View {
// #State var deck: Deck // DOES NOT WORK !!! <-------------------
let deck: Deck // WORKS (first element is updated)
var body: some View { Text(deck.name) }
}
class Model: ObservableObject {
#Published var decks: [Deck] = getData()
static func getData(changed: Bool = false) -> [Deck] {
let firstElement = changed ? "CHANGED ELEMENT" : "0"
return [Deck(firstElement, 0), Deck("1", 1), Deck("2", 2)]
}
func changeFirst() { self.decks = Self.getData(changed: true) }
}
struct ContentView: View {
#StateObject var model = Model()
var body: some View {
List {
ForEach(model.decks) { deck in
ItemView(deck: deck)
}
Button(action: model.changeFirst) {
Text("Change first item")
}
}
}
}
Tested with Xcode 13 / iPhone13 Simulator (iOS 15)
Question 1
Yes, it is expected because #State and #Published are sources of truth. #State breaks the connection with #Published and makes a copy.
Question 2
If all the changes are outside (one-way connection) you don't need wrappers of any kind for the children when dealing with value types.
If you need a two-way connection you use #Binding when dealing with a struct/value type.
https://developer.apple.com/wwdc21/10022
https://developer.apple.com/documentation/swiftui/managing-user-interface-state
https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app

Can't show view in Swift UI with layers of views and onAppear

There is a strange case where if you show a view through another view the contents (list of 3 items) of the second view won't show when values are set using onAppear. I'm guessing SwiftUI gets confused since the second views onAppear is called prior to the first views onAppear, but I still think this is weird since both of the views data are only used in their own views. Also, there is no problem if I don't use view models and instead have the data being set using state directly in the view, but then there is yet another problem that the view model declaration must be commented out otherwise I get "Thread 1: EXC_BAD_ACCESS (code=1, address=0x400000008)". Furthermore, if I check for nil in the first view on the data that is set there before showing the second one, then the second view will be shown the first time you navigate (to the first containing the second), but no other times. I also tried removing content view and starting directly at FirstView and then the screen is just black. I want to understand why these problems happen, setting data through init works but then the init will be called before it's navigated to since that's how NavigationView works, which in turn I guess I could work around by using a deferred view, but there are cases where I would like to do stuff in the background with .task as well and it has the same problem as .onAppear. In any case I would like to avoid work arounds and understand the problem. See comments for better explanation:
struct ContentView: View {
var body: some View {
NavigationView {
// If I directly go to SecondView instead the list shows
NavigationLink(destination: FirstView()) {
Text("Go to first view")
}
}
}
}
class FirstViewViewModel: ObservableObject {
#Published var listOfItems: [Int]?
func updateList() {
listOfItems = []
}
}
struct FirstView: View {
#ObservedObject var viewModel = FirstViewViewModel()
// If I have the state in the view instead of the view model there is no problem.
// Also need to comment out the view model when using the state otherwise I get Thread 1: EXC_BAD_ACCESS runtime exception
//#State private var listOfItems: [Int]?
var body: some View {
// Showing SecondView without check for nil and it will never show
SecondView()
// If I check for nil then the second view will show the first time its navigated to, but no other times.
/*Group {
if viewModel.listOfItems != nil {
SecondView()
} else {
Text("Loading").hidden() // Needed in order for onAppear to trigger, EmptyView don't work
}
}*/
// If I comment out onAppear there is no problem
.onAppear {
print("onAppear called for first view after onAppear in second view")
viewModel.updateList()
// listOfItems = []
}
}
}
class SecondViewViewModel: ObservableObject {
#Published var listOfItems = [String]()
func updateList() {
listOfItems = ["first", "second", "third"]
}
}
struct SecondView: View {
#ObservedObject var viewModel = SecondViewViewModel()
// If I set the items through init instead of onAppear the list shows every time
init() {
// viewModel.updateList()
}
var body: some View {
Group {
List {
ForEach(viewModel.listOfItems, id: \.self) { itemValue in
VStack(alignment: .leading, spacing: 8) {
Text(itemValue)
}
}
}
}
.navigationTitle("Second View")
.onAppear {
viewModel.updateList()
// The items are printed even though the view don't show
print("items: \(viewModel.listOfItems)")
}
}
}
We don't use view model objects in SwiftUI. For data transient to a View we use #State and #Binding to make the View data struct behave like an object.
And FYI initing an object using #ObservedObject is an error causing a memory leak, it will be discarded every time the View struct is init. When we are creating a Combine loader/fetcher object that we want to have a lifetime tied to the view we init the object using #StateObject.
Also you must not do id: \.self with ForEach for an array of value types cause it'll crash when the data changes. You have to make a struct for your data that conforms to Identifiable to be used with ForEach. Or if you really do want a static ForEach you can do ForEach(0..<5) {

Changes to a struct not being published in SwiftUI

I'm loading data from an API, and expecting my app to show the data once it's loaded.
In my View Model file, here's the code:
It calls a WeatherService to get the data, and populates the weather property. Weather is a struct in this case.
class WeatherViewModel: ObservableObject {
let webService = WeatherService.shared
#Published var weather:Weather?
init() {
}
func getWeather() {
webService.getWeather { weather in
if let weather = weather {
self.weather = weather
}
}
}
}
In my SwiftUI view, here's the code:
I instantiate an instance of the View Model as an ObservedObject
In the inAppear, I call the method in the view model to get the data
The first time the screen launches (using a tab bar), I see "Loading weather..." and it never goes away
If I navigate to a different tab and back, I see the weather. I can't tell if this is data from the old API call, or from the new one.
struct WeatherView: View {
#ObservedObject var weatherViewModel = WeatherViewModel()
#State var areDetailsHidden = true
var body: some View {
VStack(alignment: .leading, spacing: 0) {
if(weatherViewModel.weather == nil) {
Text("Loading weather...")
} else {
Text("Display the weather here")
}
}
.onAppear{
self.weatherViewModel.getWeather()
}
}
}
The weird thing is, if I remove the getWeather() from the onAppear and add it to the init() of the View Model, it works (although for some reason getWeather() gets called twice...). However, I want the weather info to be refreshed every time the screen is loaded.
This is caused by the:
#ObservedObject var weatherViewModel = WeatherViewModel()
being owned by the WeatherView itself.
So what happens is the weather view model changes which forces a re-render of the view which creates a new copy of the weather view model, which changes forces a re-render...
So you end up with an endless loop.
To fix it you need to move the weather view model out of the view itself so either use an #Binding and pass it in or an #EnvironmentObject and access it that way.

SwiftUI, how to bind EnvironmnetObject Int property to TextField?

I have an ObservableObject which is supposed to hold my application state:
final class Store: ObservableObject {
#Published var fetchInterval = 30
}
now, that object is being in injected at the root of my hierarchy and then at some component down the tree I'm trying to access it and bind it to a TextField, namely:
struct ConfigurationView: View {
#EnvironmnetObject var store: Store
var body: some View {
TextField("Fetch interval", $store.fetchInterval, formatter: NumberFormatter())
Text("\(store.fetchInterval)"
}
}
Even though the variable is binded (with $), the property is not being updated, the initial value is displayed correctly but when I change it, the textfield changes but the binding is not propagated
Related to the first question, is, how would I receive an event once the value is changed, I tried the following snippet, but nothing is getting fired (I assume because the textfield is not correctly binded...
$fetchInterval
.debounce(for: 0.8, scheduler: RunLoop.main)
.removeDuplicates()
.sink { interval in
print("sink from my code \(interval)")
}
Any help is much appreciated.
Edit: I just discovered that for text variables, the binding works fine out of the box, ex:
// on store
#Published var testString = "ropo"
// on component
TextField("Ropo", text: $store.testString)
Text("\(store.testString)")
it is only on the int field that it does not update the variable correctly
Edit 2:
Ok I have just discovered that only changing the field is not enough, one has to press Enter for the change to propagate, which is not what I want, I want the changes to propagate every time the field is changed...
For anyone that is interested, this is te solution I ended up with:
TextField("Seconds", text: Binding(
get: { String(self.store.fetchInterval) },
set: { self.store.fetchInterval = Int($0.filter { "0123456789".contains($0) }) ?? self.store.fetchInterval }
))
There is a small delay when a non-valid character is added, but it is the cleanest solution that does not allow for invalid characters without having to reset the state of the TextField.
It also immediately commits changes without having to wait for user to press enter or without having to wait for the field to blur.
Do it like this and you don't even have to press enter. This would work with EnvironmentObject too, if you put Store() in SceneDelegate:
struct ContentView: View {
#ObservedObject var store = Store()
var body: some View {
VStack {
TextField("Fetch interval", text: $store.fetchInterval)
Text("\(store.fetchInterval)")
}
} }
Concerning your 2nd question: In SwiftUI a view gets always updated automatically if a variable in it changes.
how about a simple solution that works well on macos as well, like this:
import SwiftUI
final class Store: ObservableObject {
#Published var fetchInterval: Int = 30
}
struct ContentView: View {
#ObservedObject var store = Store()
var body: some View {
VStack{
TextField("Fetch interval", text: Binding<String>(
get: { String(format: "%d", self.store.fetchInterval) },
set: {
if let value = NumberFormatter().number(from: $0) {
self.store.fetchInterval = value.intValue
}}))
Text("\(store.fetchInterval)").padding()
}
}
}

Why aren't views rerendered when the same class object with different values is passed as data source

I'm exploring SwiftUI and I've run into something I cannot quite figure out.
I have created a container view that can fetch data on appear as described in this post, but instead of completely changing the object referenced in the rendering view, I just load some of its properties.
The loader is an ObservableObject that the container view observes. When the loader indicates it(s value) has changed, the container view reloads its body property and displays the rendering views with the new data. However, when the object that needs to be loaded is a class, not all subviews in the body property reload.
This is some "pseudo"code of my implementation.
protocol ValueLoader: Combine.ObservableObject {
associatedtype Value
var data: Value { get set }
func load()
}
struct ValueLoadingContainerView<ValueConsumer: View,
ValueContainer: ValueLoader>: View {
#ObservedObject var valueLoader: ValueContainer
let containedView: (ValueContainer.Value) -> ValueConsumer
init(_ loader: ValueContainer,
#ViewBuilder contained: #escaping (ValueContainer.Value) -> ValueConsumer) {
self.valueLoader = loader
self.containedView = contained
}
var body: some View {
containedView(valueLoader.data)
.onAppear(perform: load)
}
private func load() {
self.valueLoader.load()
}
}
class Object {
let id: String
var title: String?
func load(from ...) {
self.title = ...
}
}
struct ConcreteLoader: ValueLoader {
#Published var data: Object
func load() {
guard shouldLoad() else { return } // To prevent infinite recursion
...
// self.objectWillChange is synthesised by conforming to
// ObservableObject and having a property with #Published
self.objectWillChange.send()
self.data.load(from: ...)
}
}
struct ObjectRenderingView: View {
let object: Object
var body: some View {
Text(object.title ?? "ObjectRenderingView is waiting...")
}
}
let object = Object(id: "1", title: nil)
ValueLoadingContainer(ConcreteLoader(object),
contained: { obj in
Text(obj.title ?? "Text is waiting...") // 1
Divider()
ObjectRenderingView(object: obj) // 2
})
When the loader has loaded the properties of object it calls the passed #ViewBuilder closure with the object again, but now its properties are loaded.
If I add print statements, I clearly see that the contained #ViewBuilder closure is called twice: once with the unloaded object and once with the loaded object. These are the same object, but the second time, the properties have been loaded.
The Text label (1) is updated correctly, changing from "Text is waiting..." to the actual title, but the ObjectRenderingView (2) does not update its subviews.
The init of ObjectRenderingView is called with the new data, but the body property is never accessed. This indicates to me that SwiftUI thinks the data has not changed and no rerendering is needed.
I think I understand why it doesn't work: the identity of the obj has not changed, so SwiftUI thinks the ObjectRenderingView does not need to be reloaded. As the identity of the value obj.title has changed from nil to the actual title, the Text view is reloaded. What I can't figure out is how to get SwiftUI to reload ObjectRenderingView as well.
Thanks!
It should be a value type. Please take a look at the docs of ObservedObject in Xcode.
If Value is not value semantic, the updating behavior for any views
that make use of the resulting Binding is unspecified.

Resources