Search code examples
iosautolayoutuikituidatepicker

UIDatePicker with .compact style doesn't respect content hugging priority


I think that the new UIDatePicker (iOS 14+) with the .compact style doesn't work correctly with AutoLayout.

Making a simple layout with a UILabel and UIDatePicker where the UIDatePicker has higher content-hugging priority should result in a layout where the UILabel is being stretched if there is too much space available but that's not what happens.

That's the result that I get:

UIDatePicker is stretched but it shouldn't be

Here is sample code:

class ViewController: UIViewController, UIGestureRecognizerDelegate {
    private let label: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = "Label"
        label.backgroundColor = .yellow
        return label
    }()
    
    private let datePicker: UIDatePicker = {
        let datePicker = UIDatePicker()
        datePicker.translatesAutoresizingMaskIntoConstraints = false
        datePicker.preferredDatePickerStyle = .compact
        return datePicker
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(label)
        view.addSubview(datePicker)
        
        label.setContentHuggingPriority(.defaultLow, for: .horizontal)
        datePicker.setContentHuggingPriority(.defaultLow + 1, for: .horizontal)
        
        NSLayoutConstraint.activate([
            label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8),
            label.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 8),
            
            label.bottomAnchor.constraint(equalTo: datePicker.bottomAnchor),
            label.trailingAnchor.constraint(equalTo: datePicker.leadingAnchor, constant: -8),
            
            datePicker.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 8),
            datePicker.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8)
        ])
    }
}

Am I missing something? Is this a known issue?


Solution

  • Works fine for me. Set the label's horizontal content hugging priority to .defaultLow-1.

    enter image description here