I have a view which sends its size to a child, so the child can update its size relative to its parent. (The child needs to be able to respond to the parents size, and also update its own size from a drag event.)
In the example below, the child sets its width to 40% of the parent in it's init. When the window is first shown, the child updates its width correctly. When you resize the window, however, the initializer is called and the size is recalculated, but the child never updates its width. The state seems to never update.
When the code is called outside of the initializer (such as pressing a button) then the state updates correctly.
Why doesn't the state update in the init after its called more than once? How would I accomplish this?
In the example below, the child sets its width to 40% of the parent in it's init. When the window is first shown, the child updates its width correctly. When you resize the window, however, the initializer is called and the size is recalculated, but the child never updates its width. The state seems to never update.
When the code is called outside of the initializer (such as pressing a button) then the state updates correctly.
Why doesn't the state update in the init after its called more than once? How would I accomplish this?
Code Block swift struct ContentView: View { var body: some View { GeometryReader { geo in ZStack { MyView(containerSize: geo.size) } .frame(maxWidth: .infinity, maxHeight: .infinity) .border(Color.green, width: 1) } } } struct MyView: View { let containerSize: CGSize @State var realSize: CGSize init(containerSize: CGSize) { self.containerSize = containerSize let newSize = CGSize(width: containerSize.width * 0.4, height: containerSize.height) print("INIT", newSize) _realSize = State(initialValue: newSize) } func updateWidth() { realSize = CGSize(width: containerSize.width * 0.4, height: containerSize.height) } var body: some View { ZStack { Button(action: { self.updateWidth() }) { Text("Update Width") } } .frame(width: realSize.width, height: realSize.height) .background(Color.blue) } }