Change text alignment of DatePicker in SwiftUI 2.0 iOS 14

Viewed 3482

Is it currently possible to change the text alignment of a DatePicker in SwiftUI 2.0?

DatePicker(selection: $birthDate, in: ...Date().stripTime(), displayedComponents: .date) {
      Text("Birthday")
}

This shows Birthday text on the left and the Date picker text right next to it but I would like it on the right side

2 Answers

Here is possible solution. Tested with Xcode 12 / iOS 14

demo

DatePicker(selection: $birthDate, in: ...Date().stripTime(), displayedComponents: .date) {
      Text("Birthday").frame(maxWidth: .infinity, alignment: .trailing)
}.fixedSize().frame(maxWidth: .infinity, alignment: .trailing)

Update:

demo2

HStack {
    Text("Birthday")
    Spacer()
    DatePicker("", selection: $birthDate, in: ...Date().stripTime(), displayedComponents: .date)
        .fixedSize()
}

My suggestion would be to include the required items in a VStack with alignment and spacing set. This keeps everything inside the VStack left aligned.

I would remove the Spacer() as this pushes the second item up to the right margin.

    VStack (alignment: .leading, spacing: 8) {
        HStack {
            Text("Birthday")
            // some other spacer
            DatePicker("", selection: $birthDate, in: ...Date().stripTime(),displayedComponents: .date)
            .fixedSize()
        }
    }
Related