首页 > 解决方案 > swiftUI中如何防止文本被截断

问题描述

我想打印出标题,以免被截断。

标题被截断

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

我试图用固定大小来解决这个问题,但是对齐方式被扭曲了

图像和文本水平插入

有没有办法解决?

标签: swiftswiftui

解决方案


您可能需要.frame(maxWidth: .infinity, alignment: .leading)VStack. 这使得 VStack 占用尽可能多的水平空间,然后将其内容 (Text(fruit.title)Text(fruit.headline)) 向左对齐。

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!
                }
            }
        }
    }
}

结果:

三行具有不同标题文本长度的水果,但都向左对齐


推荐阅读