az2902
az2902

Reputation: 428

How to prevent Text from expanding the width of a VStack

I have a VStack that contains an Image and a Text. I am setting the width (and height) of the Image to be half of the screen's width:

struct PopularNow: View {
    let item = popular[0]
    
    var body: some View {
        VStack(spacing: 5) {
            Image(item.image)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: getRect().width/2, height: getRect().width/2)
            Text(item.description)
                .font(.caption)
                .fontWeight(.bold)
                .lineLimit(0)
        }
        .padding()
        .background(Color.gray.opacity(0.1))
        .cornerRadius(15)
    }
    
    func getRect() -> CGRect {
        return UIScreen.main.bounds
    }
}

The problem is that the Text pushes and causes the VStack to expand instead of respecting the Image's width. How can I tell the Text to not grow horizontally more than the Image width and to grow "vertically" (i.e. add as many lines it needs)? I know that I can add the frame modifier to VStack itself, but it seems like a hack. I want to tell the Text to only take as much space width wise as VStack already has, not more.

This is what it looks like right now, as you can see the VStack is not half the screen's size, it's full screen size because the Text is expanding it.

screenshot of app

Upvotes: 3

Views: 2373

Answers (1)

Asperi
Asperi

Reputation: 257711

Try to fix its size, like

    VStack(spacing: 5) {
        Image(item.image)
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: getRect().width/2, height: getRect().width/2)
        Text(item.description)
            .font(.caption)
            .fontWeight(.bold)
            .lineLimit(0)
    }
    .fixedSize()         // << here !!
//   .fixedSize(horizontal: true, vertical: false)   // alternate
    .padding()

Upvotes: 3

Related Questions