如何使 SwiftUI Text multilineTextAlignment 从 Top 和 Center 开始

问题描述

enter image description here

如何使图像和文本对齐方式与 SwiftUI LazyVGrid 中的其他 3 个对齐,如下图所示?

我认为问题是如果文本是多行的,如何使文本从顶部开始。在 Android 中我可以使用 Gravity="top|center" 但在 SwiftUI 中我使用 .multilineTextAlignment(.center) 但结果不是我预期的。

enter image description here

这是我在代码中尝试的内容

      LazyVGrid(columns: gridItemLayout,spacing: 0) {
          ForEach((0...7),id: \.self) { i in
               vstack {
                    RemoteImageView(url: vm.listService[i].image_uri)
                        .frame(width: 100,height: 100)
                    Text(vm.listService[i].name)
                        .font(.body)
                        .multilineTextAlignment(.center)
                        .frame(maxWidth: .infinity,alignment: .center)
               }
         }
      }
      .padding(.horizontal,25.0)

解决方法

对于 Text 的框架,您需要:

  1. maxHeight设置为.infinity,这样它也可以垂直扩展
  2. alignment 设置为 .top,使其与顶部对齐
let names = ["Hi","Hello world","Long long text"]

let gridItemLayout = [
   GridItem(.adaptive(minimum: 80))
]

var body: some View {
    
    LazyVGrid(columns: gridItemLayout,spacing: 0) {
        ForEach((0...7),id: \.self) { i in
            VStack {
                Image(systemName: "folder")
                .frame(width: 100,height: 100)
                .background(Color.green)
                Text(names.randomElement() ?? "")
                .font(.body)
                .multilineTextAlignment(.center)
                
                /// here!
                .frame(maxWidth: .infinity,maxHeight: .infinity,alignment: .top)
            }
        }
    }
    .padding(.horizontal,25.0)
}

结果:

Grid of elements composed of an Image on top of a Text. The Image's y position is always the same,while the Text expands down when it has multiple lines.