首页 > 解决方案 > 使用verticalAlighment和alignmentGuide对齐视图的底部对齐

问题描述

我观看了 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)
}

标签: iosswiftswiftui

解决方案


注意:除非自定义对齐与 Container Alignment 参数值匹配,否则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您的更多信息,可以阅读这篇文章


推荐阅读