I'm pretty sure this won't suit all cases, but, usually, a label / button should highly resist being vertically shrunk more than its intrinsic size. On the other hand, we won't always mind if it grows larger than its intrinsic size, but we'd like to avoid it, if possible.
I, personally, find this a bit of a mouthful:
label.setContentCompressionResistancePriority(.required, forAxis: .vertical)
label.setContentHuggingResistancePriority(.defaultHigh, forAxis: .vertical)
So, let's extract them into a method, with default values as added bonus. We'll also use an enum
, so we can have "intermediate" values as cases:
enum Priority: UILayoutPriority.RawValue { // Float
case required = 1000 // .required
case aboveHigh = 751
case high = 750 // .defaultHigh
case low = 250 // .defaultLow
case fitting = 50 // .fittingSizeLevel
case none = 1 // For the cases where we don't care, since 0 is not a valid value.
// Convert it back to a UILayoutPriority.
var layoutPriority: UILayoutPriority {
return UILayoutPriority(rawValue: rawValue)
}
}
func setVerticalContentPriorities(compression compression: Priority = .required, hugging: Priority = .high) {
setContentCompressionResistancePriority(compression.layoutPriority,
for: .vertical)
setContentHuggingPriority(hugging.layoutPriority,
for: .Vertical)
}
For hugging, defaultLow
is the default, while for compression it's defaultHigh
, so we're upping them one level. Now it's much simpler to use (and easy to extrapolate to .horizontal
):
label1.setVerticalContentPriorities()
label2.setVerticalContentPriorities(hugging: .required)