Swift:如何在模式设置为仅时间的情况下调整日期选择器的宽度 [英] Swift: How to adjust width of Date Picker with mode set to Time Only
问题描述
日期选择器组件右侧似乎有一些浪费的空间:
There seems to be some wasted space towards the right of the date picker component:
并且我是否增加或减少其框架的宽度/高度值都没有关系;它保持标准尺寸.
And it doesn't matter if I increase or decrease the value of width/height of its frame; it stays the standard size.
let datePicker = UIDatePicker(frame: CGRect(x: 20, y: 100, width: 500, height: 200))
datePicker.datePickerMode = .date
view.addSubview(datePicker)
我的问题是,可以调整吗?
My question is, can it be adjusted?
所以我设法找到了它的简短形式,但只能通过故事板添加.
edit: So I managed to find its short form but thats only addable through the storyboard.
视图如下:
顶部的第一个选择器以编程方式添加,第二个选择器通过故事板添加.出于某种原因,我无法使以编程方式创建的选择器变小...
The top first picker is added programmatically and the second via storyboard. For some reason, I'm unable to make the programmatically created picker smaller...
推荐答案
你可以问问日期选择器哪个尺寸足够了 ;)
You can just ask the date picker which size is sufficient ;)
选项 A
let datePicker = UIDatePicker()
datePicker.datePickerMode = .date
// Let it size itself to its preferred size
datePicker.sizeToFit()
// Set the frame without changing the size
datePicker.frame = .init(x: 20, y: 100, width: datePicker.bounds.size.width, height: datePicker.bounds.size.height)
view.addSubview(datePicker)
选项 B
let datePicker = UIDatePicker()
datePicker.datePickerMode = .date
// Ask the picker for its preferred size
let datePickerPreferredSize = datePicker.systemLayoutSizeFitting(view.bounds.size)
// Set the frame using that size
datePicker.frame = .init(x: 20, y: 100, width: datePickerPreferredSize.width, height: datePickerPreferredSize.height)
view.addSubview(datePicker)
这篇关于Swift:如何在模式设置为仅时间的情况下调整日期选择器的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!