3

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

2
  • Why are you specifying .lineLimit(0). According to documentation, if you don't want a limit, you should pass nil - .lineLimit(nil), which I think is the default anyway Commented Apr 18, 2021 at 23:47
  • @swiftPunk something like priorities in UIKit. That type of logic... Commented Apr 19, 2021 at 6:21

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.