7.13 · View-tree exercises and long navigation stacks

Interview exercises that treat the view hierarchy as a tree: find the closest common ancestor of two views, write your own view-tree printer, and keep a very long navigation stack under control.

Mental model. A view hierarchy is a tree with a superview pointer on every node, so tree problems are solved by walking up those pointers or down subviews.

The view tree as a tree

Closest common ancestor and printing the hierarchy.

  1. Given two UIViews, find their closest common superview. How do you handle a view that is its own ancestor, or views in different trees? 7.13.1 · L3
    Every view knows its superview, so the hierarchy is a tree with parent pointers and this is the “lowest common ancestor” problem. The clean approach: walk from…
  2. Write a function that prints a UIView’s subview tree with indentation, like recursiveDescription. Recursive or iterative, and what is the real recursiveDescription? 7.13.2 · L3
    The straightforward answer is a recursive function: print the view’s line at the current depth, then call itself for each entry of subviews with depth + 1…

Many screens

What a deep navigation stack costs and how to cap it.

  1. Users can push a very large number of view controllers onto a UINavigationController. What does that cost, and how do you optimise it? 7.13.3 · L5
    A navigation controller keeps every pushed controller alive in viewControllers until it is popped (Q244), together with whatever each one retains: its model…

More in UIKit