【问题标题】:Align bottom alignment for views using verticalAlighment and alignmentGuide使用verticalAlighment和alignmentGuide对齐视图的底部对齐
【发布时间】:2026-02-12 02:55:02
【问题描述】:

我观看了 WWDC 的 Building Custom Views with SwiftUI 视频,介绍了一些使用 SwiftUI 的高级技术,但我无法对齐不在同一个 HStack 中的底部元素,请参见下图:

基本上,我想将个人资料图像与文本视图的底部对齐,但它不起作用,我使用 .alignmentGuide 修饰符遵循视频中的相同代码,但它不起作用。谢谢!

    struct MessageView : View {
    var body: some View {
        HStack {
            HStack(alignment: .center) {
                RoundImage(image: Image("turtlerock"))
                    .frame(width: 35)
                    .alignmentGuide(.bottomImageAndText) { d in
                        d[.bottom]
                    }
                VStack(alignment: .leading) {
                    Text("AR demo from Apple site ???? AR demo from Apple site ???? AR demo from Apple site ???? AR demo from Apple site ????")
                        .fontWeight(.regular)
                        .padding(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10))
                        .lineLimit(5)
                        .border(Color.gray, width: 1, cornerRadius: 15)
                        .layoutPriority(2)
                        .alignmentGuide(.bottomImageAndText) { d in
                            d[.bottom]
                        }
                    HStack {
                        Image(systemName: "heart.fill")
                            .foregroundColor(.red)
                        RoundImage(image: Image("turtlerock"))
                            .frame(height: 16)
                    }
                    .padding(.leading)
                }
            }.padding(EdgeInsets(top: 0, leading: 10, bottom:0 , trailing: 0))
            .layoutPriority(1)
            Spacer()} }
}

extension VerticalAlignment {
    private enum BottomImageAndText : AlignmentID {
        static func defaultValue(in d: ViewDimensions) -> Length {
            return d[.bottom]
        }
    }

    static let bottomImageAndText = VerticalAlignment(BottomImageAndText.self)
}

【问题讨论】:

  • 我遇到了同样的问题,我认为这在我们现在拥有的当前 Xcode 版本中不起作用。
  • @AndyHeard 感谢您的确认!让我们拭目以待验证

标签: ios swift swiftui


【解决方案1】:

注意:除非自定义对齐与容器对齐参数值匹配,否则自定义alignment guide在布局时将被忽略。

我对您的代码所做的更改:

struct MessageView : View {
var body: some View {
    HStack {
        HStack(alignment: .bottomImageAndText) {
            Image("turtlerock")
                .frame(width: 35, height: 35, alignment: .bottom)
                .alignmentGuide(.bottomImageAndText) { d in
                    d[.bottom]
            }
....

有关alignment guide的更多信息,您可以访问this article

【讨论】:

    【解决方案2】:

    为了使对齐指南正常工作,您需要将其附加到堆栈上。例如:

    HStack {
        HStack (alignment: .bottomImageAndText) {
    

    【讨论】: