Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align text at the bottom in SwiftUI

My code is as bellow:

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

The result is as bellow pic, all the view is align at the center.

Text

How to make the "pm" align "09" and "22" at the bottom such as bellow pic?

Text

like image 398
mars Avatar asked Oct 28 '25 14:10

mars


2 Answers

I just found that you can use HStack(alignment: .lastTextBaseline) or .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))
 }
like image 67
Mikrasya Avatar answered Oct 31 '25 10:10

Mikrasya


You can use VStack with Spacer() and set frame for 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))
    }
}

enter image description here

like image 31
Taeeun Kim Avatar answered Oct 31 '25 11:10

Taeeun Kim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!