SwiftUI iOS 14中日期选择器的中心对齐

SwiftUI iOS 14中日期选择器的中心对齐,ios,swift,swiftui,Ios,Swift,Swiftui,我有一个GraphicalDatePickerStyle的日期选择器,我想把它放在一个矩形的中心。我的代码: HStack { Spacer() DatePicker("", selection: $notificationTimeOnPicker, displayedComponents: .hourAndMinute).foregroundColor(Color("ChartColor")).labelsHidden()

我有一个GraphicalDatePickerStyle的日期选择器,我想把它放在一个矩形的中心。我的代码:

HStack {
        Spacer()
        DatePicker("", selection: $notificationTimeOnPicker, displayedComponents: .hourAndMinute).foregroundColor(Color("ChartColor")).labelsHidden()
                                .datePickerStyle(GraphicalDatePickerStyle())
        Spacer()
                            
        }
这就是我得到和想要的:


我如何集中我的日期选择器?看起来它的框架很宽,不知什么原因。我试图改变它的框架大小为宽度:95或更少,以使其居中,但之后我得到。。。在某些设备上键入时不使用数字。

它似乎只适用于CompactDatePickerStyle

DatePicker("", selection: $notificationTimeOnPicker, displayedComponents: .hourAndMinute)
    .foregroundColor(Color("ChartColor"))           
    .datePickerStyle(CompactDatePickerStyle())
    .clipped()
    .labelsHidden()
UIKit解决方案 在几次谷歌搜索之后,我一直在搜索结果页面的顶部找到这篇文章,所以我只想在这里回答,尽管它与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
    }
}

希望你觉得它有用

紧凑型的样式太小,其行为对于我的要求来说很奇怪,因此考虑到可访问性,我对尺寸进行了合理的硬编码:

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动态地挤压/扩展选择器以适应宽度,而不是剪切它。

尝试将
.clipped()
添加到您的picker@LeoDabus谢谢,但没帮上忙☹️这可能会有帮助