You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SwiftUI的Form组件内将DatePicker垂直居中

方案1:优先保留Form

你只需要给DatePicker添加最大高度约束,指定对齐方式为垂直居中即可实现效果,调整后代码如下:

struct TestDate: View {
    @State var chosenDate = Date()

    var body: some View {
        Form {
            DatePicker("Date", selection: $chosenDate, in: Date()..., displayedComponents: [.hourAndMinute, .date])
                .datePickerStyle(GraphicalDatePickerStyle())
                // 核心修改:让当前列表行占满Form剩余高度,子元素垂直居中
                .frame(maxHeight: .infinity, alignment: .center)
                // 可选:移除Form列表行默认的左右内边距,和原样式保持一致
                .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
        }
    }
}

这个方案完全保留了原生Form的所有特性,不需要修改外层结构。

方案2:移除Form但保留原生灰度背景

如果你需要更灵活的布局控制,可以抛弃Form,直接使用和Form完全一致的系统分组背景色,效果和原生Form无差别,代码如下:

struct TestDate: View {
    @State var chosenDate = Date()

    var body: some View {
        VStack {
            Spacer()
            DatePicker("Date", selection: $chosenDate, in: Date()..., displayedComponents: [.hourAndMinute, .date])
                .datePickerStyle(GraphicalDatePickerStyle())
                .padding(.horizontal) // 模拟Form默认的元素左右边距
            Spacer()
        }
        // 核心:和iOS原生Form完全一致的背景灰度
        .background(Color(UIColor.systemGroupedBackground).ignoresSafeArea())
    }
}

如果是适配macOS,把背景色替换为Color(NSColor.windowBackgroundColor)即可。

内容的提问来源于stack exchange,提问作者John Sorensen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 07:06:04