layoutSubviews

UIKit Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

A view must stay perfectly circular whatever size Auto Layout gives it. Where do you set the corner radius?

Options
Hint 1 of 1

When are bounds final?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Override layoutSubviews, call super, then set layer.cornerRadius = bounds.height / 2

Correct. Bounds are final there and it reruns when the size changes.

Why not the others?
  • B In init. Bounds are usually zero at init time.
  • C In the view controller's viewDidLoad. Layout hasn't run yet, so the size isn't final.
  • D In draw(_:). draw is for custom drawing, and it is expensive; it isn't layer configuration.

30-second answer

layoutSubviews runs during the layout pass, after Auto Layout has computed sizes, so bounds are final there. UIKit calls it when bounds change, subviews are added, or someone calls setNeedsLayout. Override it for geometry-dependent work like corner radii or manual frames, and call super. Don't call it directly; use setNeedsLayout or layoutIfNeeded.

Practise saying it · 30 s. No recording, just a timer

Explain layoutSubviews.

Say your answer out loud, then check which of these points you covered:

  • Runs in the layout pass
  • Bounds are final
  • setNeedsLayout vs layoutIfNeeded

Deep dive

setNeedsLayout schedules a layout pass; layoutIfNeeded runs it now if pending.

Keep it cheap: it can run many times per second during animations.

Don't change constraints inside layoutSubviews; that can loop.

In view controllers the matching hook is viewDidLayoutSubviews.

Common mistakes

  • Setting corner radius from bounds in init.
  • Calling layoutSubviews directly.

Senior take & follow-ups

Seniors explain the layout pass order and keep layoutSubviews idempotent.

Follow-up questions

Think of your answer first, then open the hint.

  1. Difference between setNeedsLayout and layoutIfNeeded?

    Show hint

    Schedule versus run now.

  2. Why might layoutSubviews loop?

    Show hint

    Changing something that invalidates layout again.

Suggest a fix if something here is wrong or out of date.