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?
The view is displayed in a sheet. in iOS 13, the DatePicker expands inline when the date value is touched. in iOS 14, instead of expanding inline, it displays modally instead. The default DatePicker style. A system style of date picker that displays each component as columns in a scrollable wheel.
To align a text view along the horizontal axis, you need to use .frame () modifier with maxWidth set to .infinity and alignment to the alignment you want. In this example, we align our text to the traling edge with .frame (maxWidth: .infinity, alignment: .trailing). Text("Hello, SwiftUI! Lorem ipsum dolor sit amet.") Align to the traling edge.
Background modifier for DatePicker works same as it works for any other view in SwiftUI. We will apply .background modifier with orange color and roundedRectangle shape. return calendar.date (from:startComponents)!
The behavior may be affected by outer environment. Sure. The surrounding body looks like this: The view is displayed in a sheet. in iOS 13, the DatePicker expands inline when the date value is touched. in iOS 14, instead of expanding inline, it displays modally instead.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With