![](/img/trans.png)
[英]Change text alignment of DatePicker in SwiftUI 2.0 iOS 14
[英]Center alignment of DatePicker in SwiftUI iOS 14
我有一个 GraphicalDatePickerStyle 的 DatePicker,我想将它放在一个矩形内。 我的代码:
HStack {
Spacer()
DatePicker("", selection: $notificationTimeOnPicker, displayedComponents: .hourAndMinute).foregroundColor(Color("ChartColor")).labelsHidden()
.datePickerStyle(GraphicalDatePickerStyle())
Spacer()
}
这就是我得到和想要的:
如何将我的 DatePicker 居中? 由于某种未知原因,它的框架看起来很宽。 我尝试将其框架大小更改为 width: 95 或更小以使其居中,但之后我在某些设备上打字时得到 ... 而不是数字。
它似乎只适用于 CompactDatePickerStyle
DatePicker("", selection: $notificationTimeOnPicker, displayedComponents: .hourAndMinute)
.foregroundColor(Color("ChartColor"))
.datePickerStyle(CompactDatePickerStyle())
.clipped()
.labelsHidden()
紧凑的样式太小,而且行为对我的要求来说很奇怪,所以我也考虑到可访问性,对大小进行了合理的硬编码:
struct ContentView: View {
@Environment(\.sizeCategory) private var sizeCategory
var body: some View {
DatePicker("Select a time", selection: .constant(Date()), displayedComponents: .hourAndMinute)
.datePickerStyle(GraphicalDatePickerStyle())
.labelsHidden()
.frame(maxWidth: CGFloat(sizeCategory.isAccessibilityCategory ? 235 : 200))
}
}
好消息是 SwiftUI 动态地挤压/扩展选择器以适应宽度而不是剪裁它。
经过几次谷歌搜索后,我一直在结果页面的顶部找到这篇文章,所以我只是在这里回答,即使它与 OP 问题并不完全相关,请随时惩罚我 ;)。
鉴于 Interface Builder 中的这种结构:
在您的视图控制器中,使用 IBOutlet 连接选择器以编程方式访问它。
@IBOutlet weak var expirationDate: UIDatePicker!
最后在 viewWillLayoutSubviews() 或 viewDidLayoutSubviews() 中放置以下代码:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let viewPicker = expirationDate.subviews.first?.subviews.first {
// Force the date picker to be centered
viewPicker.center.x = expirationDate.subviews.first!.center.x
}
}
希望你觉得它有用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.