I added an image to my body in a SwiftUI application and want to have that image cover the full width of the device, but not go over it.
In body
, I return the image object:
var body: some View {
Image("page-under-construction")
}
and the image shows up, however, it's too big:
I tried setting the frame: that affects the highlighted boundaries, but the image does not resize.
In combination, I played around with .aspectRatio(contentMode:)
, which did not seem to have any effect on the layout.
How can I have the image be effectively 100% of the screen width?
To make a SwiftUI view take all available width, we use . frame() modifier with maxWidth and maxHeight set to .
Luckily for us SwiftUI makes this very easy to do. TLDR: To make a view fill the screen or parent view, you can set the maxHeight and maxWidth to . infinity when using the frame view modifier.
The reason .aspectRatio(contentMode:)
had no effect on the layout is because you did not make the image resizable with resizeable()
.
Doing
var body: some View {
Image("page-under-construction")
.resizable()
.aspectRatio(contentMode: .fill)
}
will cause the image to be the width of the screen, but the image's aspect ratio will not be maintained. To maintain the aspect ratio, do
var body: some View {
Image("page-under-construction")
.resizable()
.aspectRatio(UIImage(named: "page-under-construction")!.size, contentMode: .fill)
}
This utilizes the .aspectRatio(aspectRatio: CGSize, contentMode: ContentMode)
version of the method your original question discussed with a dummy UIImage to access the Image's original aspect ratio.
Note: The explicitly unwrapped optional (!
) should not be a problem unless you are unsure if the image name is a valid one from your Assets folder. See this post for a comprehensive overview on Swift optionals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With