如何在 SwiftUI 中对齐底部文本

问题描述 投票:0回答:2

我的代码如下:

struct DotView: View {
    var body: some View {
        GeometryReader { geo in
            let width = geo.size.width
            HStack() {
                VStack() {
                    Circle()
                        .frame(width: width, height: width)
                    Spacer()
                    Circle()
                        .frame(width: width, height: width)
                }
            }
            
        }
    }
}


struct TestView: View {
    var body: some View {
        HStack() {
            Text("09")
            DotView()
                .frame(width: 7, height: 30, alignment: .center)
            Text("22")
            Text("PM")
                .font(.system(size: 20))
        }
        .font(.system(size: 66, weight: .medium))
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
    }
}

结果如下图,所有视图都居中对齐。

Text

如何让“pm”在底部对齐“09”和“22”,如下图?

Text

layout swiftui alignment
2个回答
2
投票

您可以将 VStack 与 Spacer() 一起使用,并为 HStack() 设置框架

struct TestView: View {
    var body: some View {
        HStack() {
            Text("09")
            DotView()
                .frame(width: 7, height: 30, alignment: .center)
            Text("22")
            VStack { // Added VStack with Spacer()
                Spacer()
                Text("PM")
                    .font(.system(size: 20))
            }
        }
        .frame(width: 300, height: 55) // Added Line, adjust frame of HStack
        .font(.system(size: 66, weight: .medium))
    }
}


0
投票

我刚刚发现你可以使用

HStack(alignment: .lastTextBaseline)
.firstTextBaseLine

HStack(alignment: .lastTextBaseline) {
    Text("09")
    DotView()
        .frame(width: 7, height: 30, alignment: .center)
    Text("22")
    VStack { // Added VStack with Spacer()
    Spacer()
    Text("PM")
        .font(.system(size: 20))
 }
© www.soinside.com 2019 - 2024. All rights reserved.