2

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 2

8

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()
}
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't quite solve it, I need the Birthday text to stay on the left, cause it needs to stay aligned to other TextFields I have above it
Finally a reasonable solution. I don't think Apple wanted anyone to apply style to the date picker
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.