Sobes.tech
Middle+

Why are properties 'Resilience to compression' needed?

sobes.tech AI

Answer from AI

Determines how unwilling a view is to shrink compared to other views when there is insufficient free space.

Properties of Compression Resistance Priority:

  • Each Dimension (Horizontal, Vertical) has its own priority.
  • Range of values: 1 (lowest) to 1000 (highest, UILayoutPriorityRequired).
  • A view with a higher priority will "resist" compression more strongly than a view with a lower priority.
  • Priority 1000 guarantees that the view will not be compressed below its intrinsic content size under any circumstances, if possible.

Usage:

  • Label with dynamic text: If you have multiple UILabels that can display text of varying lengths, using priorities helps determine which label will be compressed first if they do not fit on the screen.
  • Buttons: To prevent text on a button from being truncated, you can set a high Compression Resistance Priority for its UILabel.
  • Complex layouts: In complex Auto Layout layouts, priorities are used to resolve ambiguities when space is limited.

Example: Two UILabels in a horizontal stack.

let label1 = UILabel()
label1.text = "Short text"
label1.backgroundColor = .red

let label2 = UILabel()
label2.text = "Very very very long text"
label2.backgroundColor = .blue

let stackView = UIStackView(arrangedSubviews: [label1, label2])
stackView.axis = .horizontal
stackView.distribution = .fill // Fills the space but can compress content

// By default, priorities are the same (usually 750).
// Both labels will be compressed proportionally.

// Set a high priority for label1
label1.setContentCompressionResistancePriority(.required, for: .horizontal) // 1000
// label2 remains at priority 750

// Now, if space is limited, label2 will be compressed more,
// to keep label1's size.

Relation to Content Hugging Priority:

  • Content Hugging Priority: Determines how unwilling a view is to grow beyond its intrinsic content size when there is excess free space.
  • High Content Hugging Priority = the view "hugs" its content and does not expand.
  • High Compression Resistance Priority = the view "resists" compression and does not shrink.

These two properties work together to help Auto Layout distribute space correctly among views.