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.