Change size of image based on text SwiftUI

I am creating a widget similar to the music or podcast widget. I want to make the image larger when there is only 1 line of text, and shrink to fit up to 2 lines of text. How can I set the image size to fit the space properly?
Answered by joosttk in 622991022
Make sure you put the resizable() modifier on your image (and an .aspectRatio() set to fit). If you have this placed in a VStack or HStack with a fixed size, the size of the image will automatically resize if less space is available because of more lines of text.

You can then also give your text a lineLimit() modifier set to 2 to make sure that no more than 2 lines will be displayed.

Code Block swift
VStack {
    Image("Album")
        .resizable()
        .aspectRatio(contentMode: .fit)
    Text("Some long text here that will span two lines")
        .lineLimit(2)
}.frame(width: 200, height: 200)


Accepted Answer
Make sure you put the resizable() modifier on your image (and an .aspectRatio() set to fit). If you have this placed in a VStack or HStack with a fixed size, the size of the image will automatically resize if less space is available because of more lines of text.

You can then also give your text a lineLimit() modifier set to 2 to make sure that no more than 2 lines will be displayed.

Code Block swift
VStack {
    Image("Album")
        .resizable()
        .aspectRatio(contentMode: .fit)
    Text("Some long text here that will span two lines")
        .lineLimit(2)
}.frame(width: 200, height: 200)


Change size of image based on text SwiftUI
 
 
Q