问题
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:
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?
回答1:
Works fine for me. Set the label's horizontal content hugging priority to .defaultLow-1
.
回答2:
I have a very similar issue which is not fixed by this solution. I've reproduced in a small project and pushed into a github repo.
The UI contains a vertical UIStackView containing two UITextViews, with content hugging priorities of 249 and 248, and one DatePicker with content hugging priority of 750. When I run the app and inspect the view hierarchy I can see that the hugging priority values are retained, but the view looks as follows.
Any advice would be very welcome!
来源:https://stackoverflow.com/questions/64007536/uidatepicker-with-compact-style-doesnt-respect-content-hugging-priority