ios - 如何将图标与多行文本标签的第一行文本垂直居中?

标签 ios swiftui vertical-alignment

问题

我们希望图标与相邻 View 的第一行文本垂直居中,并且无论文本长度、图标大小或字体大小如何,我们都希望它能够对齐。换句话说,我们想要以下结果:

enter image description here

期望的结果如上:红色图标与第一行文本的中心对齐在SwiftUI中,默认的垂直对齐选项是:

.top
.center
.bottom
.firstTextBaseline
.lastTextBaseline

.center 是我们想要的单行文本,但如果我们将它用于多行文本,我们会得到:

enter image description here

如果我们使用 .firstTextBaseline,我们很接近,但它并没有使图像完全居中(随着文本大小的变化,这一点更加明显):

enter image description here

最佳答案

解决方案

我们需要结合使用对齐引用线和算术。解决方案代码如下:

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

在上面的示例中,矩形中心与第一行的中心对齐:

enter image description here

它是如何工作的

  • Rectangle是图标的替代品。
  • .firstTextBaselinealignmentGuide实际上仅用作与 HStack 匹配的 key 结盟。所以除了HStack之外没有什么区别。 , RectangleText全部都使用相同的垂直对齐方案。
  • context[VerticalAlignment.center] Rectangle的返回表示 Rectangle 的中心将与其同级 View 的其他对齐引用线对齐(从而将 Rectangle 居中)
  • 我们需要对 Text 进行额外的数学计算找到第一行文本的中心位置。该算术使用 lastTextBaselineheight整个Text计算文本基线以下的区域。通过将其添加到 firstTextBaseline除以 2,我们确定第一行文本的中心位置。此计算的结果作为对齐指南返回,用于与其同级对齐(在本例中为我们已返回的 Rectangle 的中心)

关于ios - 如何将图标与多行文本标签的第一行文本垂直居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74436141/

相关文章:

android - Google AdMob 类型

ios - 无法跟踪内存问题

Swift Combine - CFString(存储)内存泄漏

ios - 如何使用 SwiftUI Picker 更新 Realm 一对一关系?

css - div中图像的垂直对齐

html - 与基线和文本区域垂直对齐

ios - 分组部分不显示在表格 View 中

ios - React Native 图像和声音无法在真实设备上播放

ios - 带有 TabView、SwiftUI 的水平分页 ScrollView

javascript - 如何在d3js中垂直树