如何使 SwiftUI Text multilineTextAlignment 从 Top 和 Center 开始 [英] How to make SwiftUI Text multilineTextAlignment start from Top and Center
本文介绍了如何使 SwiftUI Text multilineTextAlignment 从 Top 和 Center 开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使图像和文本对齐方式与 SwiftUI LazyVGrid 中的其他 3 个对齐,如下图所示?
How can I make the image and text alignment same as 3 other in SwiftUI LazyVGrid as I expected in image below?
我认为问题是如果文本是多行的,如何使文本从顶部开始.在Android中,我可以使用gravity="top|center"但在 SwiftUI 中,我使用 .multilineTextAlignment(.center) 但结果并不如我预期.
I think the problem is how to make the text start from top if the text is multiline. In Android I can use gravity="top|center" but in SwiftUI I use .multilineTextAlignment(.center) but the result not as I expected.
这是我在代码中尝试的内容:
Here what I just try in my code:
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
的frame,你需要:
For the Text
's frame, you need to:
- 将
maxHeight
设置为.infinity
,这样它也可以垂直扩展 - 将
alignment
设置为.top
,使其与顶部对齐
- set
maxHeight
to.infinity
, so it can expand vertically too - set
alignment
to.top
, so it's aligned to the 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)
}
结果:
这篇关于如何使 SwiftUI Text multilineTextAlignment 从 Top 和 Center 开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文