GeometryReader seems to change layout of view that is using its size data. How can I avoid this?

Viewed 614

I would like my icon image to be 1/3 the width of total screen availability. My code is as follows:

    var body: some View {
        GeometryReader { geometry in
            Image(systemName: "square.dashed").resizable()
                .aspectRatio(contentMode: .fit).frame(maxWidth: geometry.size.width/3)
        }
    }

When I do this, the icon shows up in the upper left of the screen, it doesn't remain in the center like I would have thought. For example, this works properly but is not dynamic based on screen size

    var body: some View {
        Image(systemName: "square.dashed").resizable()
            .aspectRatio(contentMode: .fit).frame(maxWidth: 200)
    }

2 Answers

Here is possible solution (tested with Xcode 12.1 / iOS 14.1)

    GeometryReader { geometry in
        Image(systemName: "square.dashed").resizable()
            .aspectRatio(contentMode: .fit).frame(maxWidth: geometry.size.width/3)
            .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
Related