UIKitMidOpen-ended
How does `layoutSubviews` work and when is it called?
Explanation & Code
Answer:
layoutSubviews is called by the system whenever a view's bounds change or its subview layout needs to be recalculated. Override it for manual layout.
Code Example:
class CustomView: UIView {
override func layoutSubviews() {
super.layoutSubviews() // always call super first
// Manual frame-based layout using self.bounds
let padding: CGFloat = 16
avatarImageView.frame = CGRect(x: padding, y: padding,
width: 44, height: 44)
nameLabel.frame = CGRect(x: avatarImageView.frame.maxX + 8,
y: padding,
width: bounds.width - 72,
height: 44)
}
}
// Trigger layout
view.setNeedsLayout() // marks as dirty, updates on next render cycle
view.layoutIfNeeded() // forces immediate layout (e.g. before animation)
When it's called: bounds change, setNeedsLayout, adding/removing subviews, device rotation.
Rate your understanding: