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)
}
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)
}
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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.