Swiftui 如何将图像垂直对齐到某些文本第一行的中心?

Swiftui 如何将图像垂直对齐到某些文本第一行的中心?,swiftui,Swiftui,我有一个要点和一些长的多行文字。我希望项目符号与第一行文本的中心对齐。显然,如果字符串足够短且一行足够长,则两个视图会自动居中对齐。我对文本长度超过一行的情况很感兴趣 var body: some View { HStack { Image(systemName: "circle.fill") .font(.system(size: 8)) Text("Insert really long multil

我有一个要点和一些长的多行文字。我希望项目符号与第一行文本的中心对齐。显然,如果字符串足够短且一行足够长,则两个视图会自动居中对齐。我对文本长度超过一行的情况很感兴趣

var body: some View {
    HStack {
        Image(systemName: "circle.fill")
            .font(.system(size: 8))
        Text("Insert really long multiline string that wraps.")
    }
}
这可能吗

更新1: 将HStack对齐设置为top会将图像顶部与文本顶部对齐,如下所示

var body: some View {
    HStack(alignment: .top) {
        Image(systemName: "circle.fill")
            .font(.system(size: 8))
        Text("This is really really really really really really really really really really really really really really really really really really really really really really really really long string.")
    }
}

更新2: 我能想到的唯一选择是,除了这是UIKit

// Aligns the icon to the center of a capital letter in the first line
let offset = label.font.capHeight / 2.0

// Aligns the icon to the center of the whole line, which is different
// than above. Especially with big fonts this makes a visible difference.
let offset = (label.font.ascender + label.font.descender) / 2.0

let constraints: [NSLayoutConstraint] = [
  imageView.centerYAnchor.constraint(equalTo: label.firstBaselineAnchor, constant: -offset),
  imageView.trailingAnchor.constraint(equalTo: label.leadingAnchor, constant: -10)
]
NSLayoutConstraint.activate(constraints)

这是一个基于自定义对齐的解决方案。使用Xcode 11.4/iOS 13.4进行测试


谢谢与文字基线对齐,而不是与中心对齐。
extension VerticalAlignment {
    private enum XAlignment : AlignmentID {
        static func defaultValue(in d: ViewDimensions) -> CGFloat {
            return d[VerticalAlignment.top]
        }
    }
    static let xAlignment = VerticalAlignment(XAlignment.self)
}

struct DemoAlignFirstLine: View {

    var body: some View {
        HStack(alignment: .xAlignment) {
            Image(systemName: "circle.fill")
                .font(.system(size: 8))
                .alignmentGuide(.xAlignment) { $0.height / 2.0 }

            ZStack(alignment: .topLeading) {
                // invisible anchor, should be of same font as text
                Text("X").foregroundColor(.clear)  
                    .alignmentGuide(.xAlignment) { $0.height / 2.0 }

                // main text
                Text("This is really really really really really really really really really really really really really really really really really really really really really really really really long string.")
            }
        }
    }
}