Search code examples
iosswiftuser-interfaceuidatepicker

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:

enter image description here

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.

Heres the view:

enter image description here

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...


Solution

  • You can just ask the date picker which size is sufficient ;)

    Option 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)
    

    Option 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)