Philipp Rosengart
Philipp Rosengart

Reputation: 733

Swift iOS14 DatePicker text alignment

I want my date picker to show the text right aligned as it is contained in an right aligned tableView. I'm using the iOS 14 default style were selecting the date picker ends up in a popover to select the date, so by default the label is left aligned when the popover is not showing. I tried using datePicker.contentHorizontalAlignment = .right but nothing is changing. Is there any other way to change the alignment as it is looking strange that way? DatePicker

Upvotes: 8

Views: 5204

Answers (1)

androidguy
androidguy

Reputation: 3177

There's no explicit way to do this, since the widget itself seems to not honor the content alignment; BUT: I have found a way to do this that works with iOS currently. At some point the date picker creates a UILabel, seemingly with a 'leading' constraint, no matter what content alignment. But, we can override what that 'leading' means with clever use of semanticContentAttribute.

datePicker.semanticContentAttribute = .forceRightToLeft
datePicker.subviews.first?.semanticContentAttribute = .forceRightToLeft
  1. This code can't crash the app, even if the widget changes, it safely access the first subview and sets an official API on it.
  2. It does work with iOS 14.2; and
  3. Supposing, in iOS 14.3 or 15+, Apple changes the widget structure such that this trick doesn't work, perhaps because there's another nested view, all that could happen is the layout goes back to the default.

It's possible only the second line of code is necessary, but my first attempt was with the first line, which didn't work, so I added the second line.

Upvotes: 15

Related Questions