SwiftUI日期选择器在首次选择日期时更改大小。

5
我在底部视图中有一个日期选择器。 当底部视图打开后,第一次选择日期时,日期选择器的高度会发生变化。 附:如果我使用 .frame 设置日期选择器的自定义高度,则日期选择器将被挤压在框架内。

enter image description here

    var body: some View {
    VStack {
        HStack {
            Text("date_picker_title".ld())
                .font(.custom(Font.rRegular, size: 12))
                .padding()
            Spacer()
        }
        HStack {
            Text(date.prettyDate)
                .font(.custom(Font.rMedium, size: 28))
            Spacer()
            Text(date.prettyHour)
                .font(.custom(Font.rMedium, size: 28))
        }.padding(.horizontal)
        Seperator(cellHeight: 0).frame(height: 2)

        Spacer().frame(height: 6)
        DatePicker("", selection: $date, in: Date()..., displayedComponents: .date)
            .datePickerStyle(.graphical)
            .labelsHidden()
            .tint(Color.appPurple)
            .padding(.horizontal)
            .padding(.bottom, -10)
        Seperator(cellHeight: 0).frame(height: 2)
        HStack {
            Text("date_picker_enter_time".ld())
                .font(.custom(Font.rRegular, size: 12))
            DatePicker("", selection: $date, displayedComponents: .hourAndMinute)
                .labelsHidden()
                .tint(Color.appPurple)
            Spacer()
        }.padding()
        
        HStack {
            Button {
                completion(nil)
            } label: {
                Text("date_picker_cancel".ld())
                    .font(.custom(Font.rRegular, size: 14))
                    .foregroundColor(Color.appPurple)
            }
            Spacer()
            Button {
                completion(date)
            } label: {
                Text("date_picker_ok".ld())
                    .font(.custom(Font.rRegular, size: 14))
                    .foregroundColor(Color.appPurple)
            }
        }.padding(.horizontal)
        Spacer().frame(height: 50)
    }
    .frame(maxWidth: .infinity)
    .background(Color.appLightPurple)
    .padding(.bottom, -50)
}
2个回答

5

我遇到了类似的问题,并且收到了控制台警告:“UICalendarView 的高度小于其可以呈现内容的高度;默认为最小高度”

我发现 这个答案 可以设置框架宽度。虽然不是最佳解决方案,但似乎解决了我的问题。

DatePicker(selection: $date, displayedComponents: .date)
   .datePickerStyle(.graphical)
   .frame(width: 320) // Bugfix for AutoLayout-Issue

0
我不知道为什么,但将日期选择器的ID设置为被选中的日期似乎可以解决这个跳动问题。
    DatePicker("title", selection: $fromDate, displayedComponents: .date)
        .datePickerStyle(.graphical)
        .id(fromDate) // Magically stops it from jumping in size on first selection

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接