Home > Mobile >  How can I make text resize automatically to fit within a frame in swiftUI?
How can I make text resize automatically to fit within a frame in swiftUI?

Time:06-19

I need to make text fit within a frame. I have a view which is essentially a rectangular box with an image and text. If the text is too long I get "..." and the text is not in the view. How can I avoid this?

Here is my code:

 var body: some View {
        
            
                VStack(alignment: .center, spacing: 0) {
                    
                    WebImage(url: URL(string: productData.product_image))
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .cornerRadius(15)
                        .clipped()
                        .padding(5)
                    
                   
                Text(productData.product_name)
                    .font(.title2)
                    .fontWeight(.bold)
                    .foregroundColor(.black)
                    .padding()

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

    }

CodePudding user response:

you have two options

1 - first one is to make a scale factor to the text depending on it's frame so when you have a text of size 30 width and 30 height and the text is 50 word that will not fit into the text frame so you could use and the text will get smaller to fit into the frame of text

Text("text of 50 word").frame(width: 30, height: 30, alignment: .center).minimumScaleFactor(0.5)     

2 - second one is to use fixed-size modifier which will make the text fit into the text frame and make the text scrollable whether in vertical position or horizontal position using

fixedSize(horizontal: Bool, vertical: Bool)

check Apple docs for that https://developer.apple.com/documentation/swiftui/menu/fixedsize(horizontal:vertical:)

  • Related