0

I'm working in SwiftUI and have a GeometryProxy as a property of class used on a view & subview. My code is working fine, but I'd like the subview to render in Preview properly, but to do this, the PreviewProvider needs to have valid GeometryProxy data in a property (geo) of the class I've created (LayoutData). SwiftUI doesn't let me update an object's property as indicated in the comments in the code below. Is there some other way I might be able to get a valid GeometryProxy & use this to update a property in my LayoutData class when using the PreviewProvider? Code otherwise works great & I can run my Live Preview from the parent View, but it would be nice to see things rendered properly on my subview - which I could do if I could pass in my LayoutData object with a valid GeometryProxy property.

Really, all I need from the GeometryProxy is the screen width, so I could use just that in my LayoutData class, but I don't want to use UIScreen.main.width since this will be deprecated & I don't know of another way to get a valid width other than GeometryReader. Here is the code I've attempted, but of course, the comment line trying to update a variable property inside a View, as I've shown, can't be done in SwiftUI.

struct ButtonLayout_Previews: PreviewProvider {
    static var previews: some View {
        var layoutData = LayoutData()
        GeometryReader { previewGeo in
            layoutData.geo = previewGeo // You can't do this in SwiftUI
            ButtonLayoutView(resultMessage: .constant(""), layoutData: layoutData)
        }
    }
}

I also know that I can introduce an additional, separate GeometryProxy property for the subview & pass that in as an extra property, using the GeometryReader setup, above, but I don't want to add an extra variable to my code if it's not needed & if I can use the Preview with the GeometryProxy property of my LayoutData class. Thanks for any ideas!

Gallaugher
  • 1,593
  • 16
  • 27

1 Answers1

0

I was able to make the assignment using an empty let statement, and including the assignment after the equal, like below. Any concerns with this? It seems like I'm tricking SwiftUI into accepting an assignment where it normally wouldn't, but this works:

struct ButtonLayout_Previews: PreviewProvider {
    static var previews: some View {
        let layoutData = LayoutData()
        GeometryReader { previewGeo in
            let _ = layoutData.geo = previewGeo
            ButtonLayoutView(resultMessage: .constant(""), layoutData: layoutData)
        }
    }
}
Gallaugher
  • 1,593
  • 16
  • 27