首页 > 解决方案 > 如何让 LazyVStack 适应它的列号?

问题描述

我需要 SwiftUI 来确定在 LazyVStack 中使用多少列并根据内容调整它的宽度。为此,我决定使用 .adaptive 网格项,看看:

struct ContentView: View {
let shortNames: [String] = ["Fay", "May", "Chi", "Cal", "Dee", "An", "Rob"]
let longNames: [String] = ["Christofer", "Alexander", "Leopold", "Anastasia", "Jacquelin", "Charlotte"]

var body: some View {
    LazyVGrid(columns: [GridItem(.adaptive(minimum: 80))],
              content: {
                ForEach(longNames, id: \.self) { name in
                    Text("\(name)")
                        .padding()
                        .background(Color.gray)
                }
              })
}

这就是我得到的: 短名称显示在 4 列中,而长名称分为两行和 4 列

那么对于 SwiftUI 来说,保持长文本牢不可破并将其列调整为更合适的大小并制作 3 列而不是 4 列不是更好吗? 像这样

我试过了:

Text("\(name)")
    .lineLimit(1) // That keeps the text in one line, 
                  // but it gets truncated at the end.
                  // And SwiftUI doesn't expand column width.
    .minimumScaleFactor(0.5) // That shrinks the text, 
                             // but doesn't make SwiftUI expand the column width
    .fixedSize() // Still 4 columns
    .padding()
    .background(Color.gray)

标签: swiftui

解决方案


推荐阅读