JeeNi
JeeNi

Reputation: 201

How to prevent text from being cut off in swiftUI

I want to print out the headline so that it doesn't get cut off.

Headline is truncated

VStack(alignment: .leading, spacing: 5) {
    Text(fruit.title)
        .font(.title2)
        .fontWeight(.bold)
    Text(fruit.headline)
        .font(.caption)
        .foregroundColor(Color.secondary)
}

I tried to solve this problem with a fixed size, but the alignment was warped

Image and text inset horizontally

Is there a way to solve?

Upvotes: 2

Views: 4764

Answers (1)

aheze
aheze

Reputation: 30506

You might need a .frame(maxWidth: .infinity, alignment: .leading) on the VStack. This makes the VStack take up as much horizontal space as possible, then aligns its contents (Text(fruit.title) and Text(fruit.headline)) to the left.

struct Fruit: Hashable {
    var title: String
    var headline: String
}
struct ContentView: View {
    let fruits = [
        Fruit(title: "Pomegranate", headline: "Sweet, bell-shaped fruits that have been enjoyed since ancient times. They can be eaten crisp or soft."),
        Fruit(title: "Plum", headline: "Plums are a very nutritious fruit. An excellent source of vitamins, minerals, fiber and antioxidants."),
        Fruit(title: "Apple", headline: "An apple"),
    ]
    
    var body: some View {
        VStack {
            ForEach(fruits, id: \.self) { fruit in
                HStack {
                    Image(fruit.title)
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .frame(width: 80, height: 80)

                    VStack(alignment: .leading, spacing: 5) {
                        Text(fruit.title)
                            .font(.title2)
                            .fontWeight(.bold)
                        Text(fruit.headline)
                            .font(.caption)
                            .foregroundColor(Color.secondary)
                            
                    }
                    .frame(maxWidth: .infinity, alignment: .leading) /// here!
                }
            }
        }
    }
}

Result:

Three rows of fruits with varying headline text lengths, but all aligned left

Upvotes: 2

Related Questions