问题
我们希望图标与相邻 View 的第一行文本垂直居中,并且无论文本长度、图标大小或字体大小如何,我们都希望它能够对齐。换句话说,我们想要以下结果:
期望的结果如上:红色图标与第一行文本的中心对齐在SwiftUI中,默认的垂直对齐选项是:
.top
.center
.bottom
.firstTextBaseline
.lastTextBaseline
.center
是我们想要的单行文本,但如果我们将它用于多行文本,我们会得到:
如果我们使用 .firstTextBaseline
,我们很接近,但它并没有使图像完全居中(随着文本大小的变化,这一点更加明显):
最佳答案
解决方案
我们需要结合使用对齐引用线和算术。解决方案代码如下:
struct ContentView: View {
var body: some View {
HStack(alignment: .firstTextBaseline) {
Rectangle()
.fill(.red)
.frame(width: 16, height: 16)
.alignmentGuide(.firstTextBaseline) { context in
context[VerticalAlignment.center]
}
Text(greeting)
.font(.title3)
.background(.blue)
.alignmentGuide(.firstTextBaseline) { context in
let remainingLine = (context.height - context[.lastTextBaseline])
let lineHeight = context[.firstTextBaseline] + remainingLine
let lineCenter = lineHeight / 2
return lineCenter
}
}
}
}
在上面的示例中,矩形中心与第一行的中心对齐:
它是如何工作的
Rectangle
是图标的替代品。.firstTextBaseline
的alignmentGuide
实际上仅用作与HStack
匹配的 key 结盟。所以除了HStack
之外没有什么区别。 ,Rectangle
和Text
全部都使用相同的垂直对齐方案。context[VerticalAlignment.center]
Rectangle
的返回表示Rectangle
的中心将与其同级 View 的其他对齐引用线对齐(从而将Rectangle
居中)- 我们需要对
Text
进行额外的数学计算找到第一行文本的中心位置。该算术使用lastTextBaseline
和height
整个Text
计算文本基线以下的区域。通过将其添加到firstTextBaseline
除以 2,我们确定第一行文本的中心位置。此计算的结果作为对齐指南返回,用于与其同级对齐(在本例中为我们已返回的Rectangle
的中心)
关于ios - 如何将图标与多行文本标签的第一行文本垂直居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74436141/