Mxyb
Mxyb

Reputation: 415

How Do I Align Views Within A VStack In A Frame In SwiftUI?

I have a 'tile' that displays three things. A photo of the product, the title of the product and type of product (see photo). When the title of the product is longer, the photo is pushed up and made smaller as expected. I need to make the title and type of product go lower down in the frame so the photo can be the main focus. I am unsure how to achieve this.

Here is the code for this view:

 VStack(alignment: .center, spacing: 0) {
                    
                    WebImage(url: URL(string: productData.product_profileImage))
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .clipped()
                        .padding(5)
               
                    Text(productData.product_name)
                    .font(.title2)
                    .fontWeight(.bold)
                    .foregroundColor(.black)
                    .minimumScaleFactor(0.5)
                    .multilineTextAlignment(.center)
                    .padding()

                    
                Text(productData.product_type)
                    .font(.caption)
                    .foregroundColor(.gray)
                    .lineLimit(2)
                    .padding()
            }
                .frame(width: 150, height: 200)

Here is a photo of what it currently looks like: how it looks

Upvotes: 1

Views: 483

Answers (2)

Hardik Shekhat
Hardik Shekhat

Reputation: 1888

You can also achieve it by wrapping your Text content in a separate VStack.

VStack(alignment: .center, spacing: 0) {
        
        WebImage(url: URL(string: productData.product_profileImage))            
            .resizable()
            .aspectRatio(contentMode: .fit)
            .clipped()
            .padding(5)
        
        VStack { //Wrap your text content into VStack
            Text("Example Product A")
                .font(.title2)
                .fontWeight(.bold)
                .foregroundColor(.black)
                .minimumScaleFactor(0.5)
                .multilineTextAlignment(.center)
                .padding()
            
            
            Text("Clothing")
                .font(.caption)
                .foregroundColor(.gray)
                .lineLimit(2)
                .padding()
        }

}.frame(width: 150, height: 200)

Upvotes: 0

Asperi
Asperi

Reputation: 258443

Give a higher layout priority to image, so it would lay out first and keep all needed space, like

WebImage(url: URL(string: productData.product_profileImage))
    .resizable()
    .aspectRatio(contentMode: .fit)
    .clipped()
    .padding(5)
    .layoutPriority(1)     // << here !!

Tested with Xcode 13.4 / iOS 15.5

Upvotes: 1

Related Questions