SwiftUI View is reinitialized when #Binding Property has not been modified - ios

I am executing a SwiftUI playground that contains 2 labels and 2 buttons that modified the value of these labels.
I've stored the value of these labels in a #ObservableObject. Whene I modify the value of any of these properties, both views CustomText2 and CustomText3 are reinitialized, even the one that his values has not changed.
Code:
final class ViewModel: ObservableObject {
#Published var title: Int
#Published var title2: Int
init(title: Int = 0, title2: Int = 0) {
self.title = title
self.title2 = title2
}
}
struct ContentView: View {
#StateObject var viewModel = ViewModel()
var body: some View {
VStack {
Button(
action: {
viewModel.title += 1
}, label: {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
}
)
CustomText1(
title: $viewModel.title
)
Button(
action: {
viewModel.title2 += 1
}, label: {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
}
)
CustomText2(
title: $viewModel.title2
)
}
.padding()
}
}
struct CustomText1: View {
#Binding var title: Int
init(
title: Binding<Int>
) {
self._title = title
}
var body: some View {
Text("\(title)")
.foregroundColor(.black)
}
}
However if I store both properties as #State in the view and I modify them, the CustomTexts are not reinitialized, they just update their value in the body without executing an init.
Why are they getting reinitialized when I store both properties in the ViewModel?
I've tried to make the views conforming Equatable but they're reinitialized.
Can be a performance problem if the views are initialized many times?
I am interested in not having the subviews reinitialized because I want to perform custom stuff in the init of some subviews.

When you have one StateObject that encompasses multiple State variables, change in one will redraw the entire view. In your case, any change in any variable in viewModel will trigger the publisher of viewModel and reload ContentView
Also we are not supposed to make any assumptions on when a View will be redrawn, as this might change with different versions of SwiftUI. Its better to move this custom stuff you are doing in the init of views to some other place(if it can be). Init should only do work needed to redraw the view with the new state parameters and nothing else.

#ObservableObject is for model data, not view data.
The reason is when using lets or #State vars, SwiftUI uses dependency tracking to decide if body needs to be called and in your case body doesn't use the values anywhere so there is no need to call it.
It can't track objects in the same way, if there is a #StateObject declared then body is called regardless if any properties are accessed, so it's best to start with #State value types and only change to #StateObject when you really need features of a reference type. Not very often now we have .task which is the place to put your custom async work.

Related

Why is this SwiftUI state not updated when passed as a non-binding parameter?

Here's what I want to do:
Have a SwiftUI view which changes a local State variable
On a button tap, pass that variable to some other part of my application
However, for some reason, even though I update the state variable, it doesn't get updated when it's passed to the next view.
Here's some sample code which shows the problem:
struct NumberView: View {
#State var number: Int = 1
#State private var showNumber = false
var body: some View {
NavigationStack {
VStack(spacing: 40) {
// Text("\(number)")
Button {
number = 99
print(number)
} label: {
Text("Change Number")
}
Button {
showNumber = true
} label: {
Text("Show Number")
}
}
.fullScreenCover(isPresented: $showNumber) {
SomeView(number: number)
}
}
}
}
struct SomeView: View {
let number: Int
var body: some View {
Text("\(number)")
}
}
If you tap on "Change Number", it updates the local state to 99. But when I create another view and pass this as a parameter, it shows 1 instead of 99. What's going on?
Some things to note:
If you uncomment Text("\(number)"), it works. But this shouldn't be necessary IMO.
It also works if you make SomeView use a binding. But for my app, this won't work. My actual use case is a 'select game options' view. Then, I will create a non-SwiftUI game view and I want to pass in these options as parameters. So, I can't have bindings all the way down my gaming code just because of this bug. I want to just capture what the user enters and create a Parameters object with that data.
It also works if you make it a navigationDestination instead of a fullScreenCover. ¯\(ツ)/¯ no idea on that one...
A View is a struct, therefore its properties are immutable, so the view can not change its own properties. This is why changing the property named number from inside the body of the view needs this property to be annotated with a #State property wrapper. Thanks to Swift and SwiftUI, transparent read and write callbacks let the value being seen changed. So you must not pass number as a parameter of SomeView() when calling fullScreenCover(), but pass a reference to number, for the callbacks to be systematically called: $number. Since you are not passing an integer anymore to construct struct SomeView, the type of the property named number in this struct can not any longer be an integer, but must be a reference to an integer (namely a binding): use the #Binding annotation for this.
So, replace SomeView(number: number) by SomeView(number: $number) and let number: Int by #Binding var number: Int to do the job.
Here is the correct source code:
import SwiftUI
struct NumberView: View {
#State var number: Int = 1
#State private var showNumber = false
var body: some View {
NavigationStack {
VStack(spacing: 40) {
// Text("\(number)")
Button {
number = 99
print(number)
} label: {
Text("Change Number")
}
Button {
showNumber = true
} label: {
Text("Show Number")
}
}
.fullScreenCover(isPresented: $showNumber) {
SomeView(number: $number)
}
}
}
}
struct SomeView: View {
#Binding var number: Int
var body: some View {
Text("\(number)")
}
}
After all that said to obtain a valid source code, their is a little trick that has not been explained up to now: if you simply replace in your source code Text("Change Number") by Text("Change Number \(number)"), without using $ reference nor #Binding keywords anywhere, you will see that the problem is also automatically solved! No need to use #binding in SomeView! This is because SwiftUI makes optimizations when building a tree of views. If it knows that the displayed view changed (not only its properties), it will compute the view with updated #State values. Adding number to the button label makes SwiftUI track changes of the number state property and it now updates its cached value to display the Text button label, therefore this new value will be correctly used to create SomeView. All of that may be considered as strange things, but is simply due to optimizations in SwiftUI. Apple does not fully explain how it implements optimizations building a tree of views, there are some informations given during WWDC events but the source code is not open. Therefore, you need to strictly follow the design pattern based on #State and #Binding to be sure that the whole thing works like it should.
All of that said again, one could argue that Apple says that you do not have to use #Binding to pass a value to a child view if this child view only wants to access the value: share the state with any child views that also need access, either directly for read-only access, or as a binding for read-write access (https://developer.apple.com/documentation/swiftui/state). This is right, but Apple says in the same article that you need to place [state] in the highest view in the view hierarchy that needs access to the value. With Apple, needing to access a value means that you need it to display the view, not only to do other computations that have no impact on the screen. This is this interpretation that lets Apple optimize the computation of the state property when it needs to update NumberView, for instance when computing the content of the Text("Change Number \(number)") line. You could find it really tricky. But there is a way to understand that: take the initial code you wrote, remove the #State in front of var number: Int = 1. To compile it, you need to move this line from inside the struct to outside, for instance at the very first line of your source file, just after the import declaration. And you will see that it works! This is because you do not need this value to display NumberView. And thus, it is perfectly legal to put the value higher, to build the view named SomeView. Be careful, here you do not want to update SomeView, so there is no border effects. But it would not work if you had to update SomeView.
Here is the code for this last trick:
import SwiftUI
// number is declared outside the views!
var number: Int = 1
struct NumberView: View {
// no more state variable named number!
// No more modification: the following code is exactly yours!
#State private var showNumber = false
var body: some View {
NavigationStack {
VStack(spacing: 40) {
// Text("\(number)")
Button {
number = 99
print(number)
} label: {
Text("Change Number")
}
Button {
showNumber = true
} label: {
Text("Show Number")
}
}
.fullScreenCover(isPresented: $showNumber) {
SomeView(number: number)
}
}
}
}
struct SomeView: View {
let number: Int
var body: some View {
Text("\(number)")
}
}
This is why you should definitely follow the #State and #Binding design pattern, taking into account that if you declare a state in a view that does not use it to display its content, you should declare this state as a #Binding in child views even if those children do not need to make changes to this state. The best way to use #State is to declare it in the highest view that needs it to display something: never forget that #State must be declared in the view that owns this variable; creating a view that owns a variable but that does not have to use it to display its content is an anti-pattern.
Since number isn't read in body, SwiftUI's dependency tracking detect it. You can give it a nudge like this:
.fullScreenCover(isPresented: $showNumber) { [number] in
Now a new closure will be created with the updated number value whenever number changes. Fyi the [number] in syntax is called a "capture list", read about it here.
Nathan Tannar gave me this explanation via another channel which I think gets to the crux of my problem. It does seem that this is a SwiftUI weirdness caused by knowing when and how it updates views based on state. Thanks Nathan!
It’s because the number isn’t “read” in the body of the view. SwiftUI is smart in that it only triggers view updates when a dependency of the view changes. Why this causes issues with the fullScreenCover modifier is because it captures an #escaping closure for the body. Which means it’s not read until the cover is presented. Since its not read the view body will not be re-evaluated when the #State changes, you can validate this by setting a breakpoint in the view body. Because the view body is not re-evaluated, the #escaping closure is never re-captured and thus it will hold a copy of the original value.
As a side note, you’ll find that once you present the cover for the first time and then dismiss, subsequent presentations will update correctly.
Arguably this seems like a SwiftUI bug, the fullScreenCover probably shouldn’t be #escaping. You can workaround by reading the number within the body, or wrapping the modifier with something like this, since here destination is not #escaping captured so the number will be read in the views body evaluation.
struct FullScreenModifier<Destination: View>: ViewModifier {
#Binding var isPresented: Bool
#ViewBuilder var destination: Destination
func body(content: Content) -> some View {
content
.fullScreenCover(isPresented: $isPresented) {
destination
}
}
}

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

How can I dynamically add SwiftUI Views to a parent View?

Is it possible to add multiple SwiftUI Views to a parent View dynamically & programmatically?
For example suppose we have a basic View such as:
struct MyRectView: View {
var body: some View {
Rectangle()
.fill(Color.red)
.frame(width: 200, height: 200)
}
}
And a Button defined as:
struct MyButtonThatMakesRects: View {
var body: some View {
Button(
action: {
// Create & add Views to parent here?
// ...
},
label: {
Text("tap to create a Rect")
}
)
}
}
Is there any way I can create multiple instances of MyRectView in a parent View when MyButtonThatMakesRects is tapped?
My initial thinking was in line with how I would do this in UIKit. That being on button tap, create a new UIView(), and then use .addSubview(...) to add it to a parent. Not sure if SwiftUI has similar functionality. Or maybe there is a simpler way to do this that I'm not seeing?
SwiftUI is functional and reactive, so its output is entirely a reflection of state. You'll have to store and manipulate state that results in a SwiftUI view with your desired outcome. The view is reconstructed from scratch every time its state changes. (Not really, as there's some efficient diffing under the hood, but it's a good mental model to use.)
The simplest way that SwiftUI provides is the #State property wrapper, so a version of what you're asking for would look something like this:
struct RootView: View {
#State private var numberOfRects = 0
var body: some View {
VStack {
Button(action: {
self.numberOfRects += 1
}) {
Text("Tap to create")
}
ForEach(0 ..< numberOfRects, id: \.self) { _ in
MyRectView()
}
}
}
}
I'm guessing your desired end result is more complicated than that, but you can use #State or use a property pointing to a separate class that handles your state/model, marked with the #ObservedObject wrapper, to get to whatever you need.

What does Apple mean by #ObjectBinding should be passed over through view?

I've been newly studying SwiftUI.
And since I've seen Data flow over SwiftUI video from Apple explaining difference between #ObjectBinding and #EnvironmentObject, a question has come to my mind.
What does apple mean by :
You have to pass around the model from hop to hop in #ObjectBinding ? (29':00")
Do we have to pass the object using #binding in another views for using them ?
What if we don't use #binding and reference to it using another #ObjectBinding ?
Does that make an inconvenience or make SwiftUI not to work correctly or views not being sync with each other ?
[Edit: note that #ObjectBinding is no longer around; instead you can use #State to mark an instance variable as requiring a view refresh when it changes.]
When a view declares an #State or #Binding variable, its value must be explicitly passed from the view's parent. So if you have a long hierarchy of views with some piece of data from the top being used in the bottom, you must code every level of that hierarchy to know about and pass down the data.
In his comment at 29:00, he is contrasting this to using #EnvironmentVariable in a child view, which searches the whole hierarchy for that piece of data. This means any views that do not explicitly need the data can effectively ignore it. Registering a variable needs only be done once (via .environmentObject(_) on a view).
Here is a contrived example. Given some data type conforming to ObservableObject,
class SampleData: ObservableObject {
#Published var contents: String
init(_ contents: String) {
self.contents = contents
}
}
Consider this view hierarchy:
struct ContentView: View {
#State private var data = SampleData("sample content")
var body: some View {
VStack {
StateViewA(data: self.data)
EnvironmentViewA()
.environmentObject(self.data)
}
}
}
struct StateViewA: View {
#State var data: SampleData
var body: some View {
StateViewB(data: self.data)
}
}
struct StateViewB: View {
#State var data: SampleData
var body: some View {
Text(self.data.contents)
}
}
struct EnvironmentViewA: View {
var body: some View {
EnvironmentViewB()
}
}
struct EnvironmentViewB: View {
#EnvironmentObject var data: SampleData
var body: some View {
Text(self.data.contents)
}
}
The result in ContentView will be two views that display the same piece of text. In the first, StateViewA must pass the data on to its child (i.e. the model is passed from "hop to hop"), whereas in the second, EnvironmentViewA does not have to be aware of the data at all.

One view does not rerender when #State var changes based on Picker selection

Trying to build a simple MacOS app using SwiftUI. I have a View that contains a Picker bound to a State var. As a sanity check I have added a Text Views (the dwarves one and the volumes...itemName) that should also change with the Picker changes. And they do, but the View I want to rerender (the FileList) does not.
I suspect it has something to do with how I am trying to pass the new FileSystemItem (internal class) to the FileList. Like when the FilePanel rerenders the volumeSelection is back to 0 and the state is applied afterwards. So my problem is that I seem to be missing a fundamental concept on how this data is supposed to flow. I have gone through the WWDC info again and been reading other articles but I am not seeing the answer.
The desired behavior is changing the selection on the picker should cause a new FileSystemItem to be displayed in the FileList view. What is the right way to get this to happen? To state it more generically, how to you get a child view to display new data when a Picker selection changes?
struct FilePanel: View
{
#State var volumeSelection = 0
#State var pathSelection = 0
var volumes = VolumesModel() //should be passed in?
var dwarves = ["Schlumpy","Wheezy","Poxxy","Slimy","Pervy","Drooly"]
var body: some View {
VStack {
Picker(selection: $volumeSelection, label:
Text("Volume")
, content: {
ForEach (0 ..< volumes.count()) {
Text(self.volumes.volumeAtIndex(index: $0).itemName).tag($0)
}
})
FileList(item:volumes.volumeAtIndex(index: volumeSelection)).frame(minWidth: CGFloat(100.0), maxHeight: .infinity)
Text(dwarves[volumeSelection])
Text(volumes.volumeAtIndex(index: volumeSelection).itemName)
}
}
}
struct FileList: View {
#State var item : FileSystemItem
var body: some View {
VStack {
List(item.childItems){fsi in
FileCell(expanded:false, item: fsi)
}
Text(item.itemName)
}
}
}
#State is a state private to to the owning view, FileList will never see any change.
If VolumesModel was a simple struct turning FileList.item into a binding (in-out-state) may already work (the caller still needs to turn it's #State into a binding when passing it to the dependent using the $):
struct FileList: View {
#Binding var item : FileSystemItem
...
}
However, it feels as if VolumesModel was a more complex object having an array of members.
If this is the case the above will not suffice:
VolumesModel needs to be a class adopting ObservableObject
VolumesModel's important members need a bindable wrapper (#Published)
FileList.item should be turned into #ObservedObject (instead of #State or #Binding)
FilePanel.volumes also to be #ObservedObject wrapped
Hope that helps or at least points you into the right direction.

Resources