Search code examples
iosdatepickerswiftuiios14

Change text alignment of DatePicker in SwiftUI 2.0 iOS 14


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


Solution

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