2

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 Answers2

3

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)
    }
Asperi
  • 228,894
  • 20
  • 464
  • 690
0

If you ever want to center a view inside a GeometryReader, rather than aligning to the top-left corner, add a second frame that makes it fill the full space of the container, like this:

GeometryReader { geo in
Image("Example")
    .resizable()
    .scaledToFit()
    .frame(width: geo.size.width * 0.8)
    .frame(width: geo.size.width, height: geo.size.height)

}

from: https://www.hackingwithswift.com/books/ios-swiftui/resizing-images-to-fit-the-screen-using-geometryreader