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.
- Given two UIViews, find their closest common superview. How do you handle a view that is its own ancestor, or views in different trees?
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… - Write a function that prints a UIView’s subview tree with indentation, like recursiveDescription. Recursive or iterative, and what is the real recursiveDescription?
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.
- Users can push a very large number of view controllers onto a UINavigationController. What does that cost, and how do you optimise it?
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
- 7.1 · Hit testing, the responder chain and gesture recognisers
- 7.2 · UIView and CALayer, frame, bounds and center
- 7.3 · View controller lifecycle, containment, presentation and transitions
- 7.4 · Navigation, tab, split and page controllers
- 7.5 · Compositional layout, diffable data sources, cell reuse and prefetching
- 7.6 · UITableView, still asked and still everywhere
- 7.7 · Trait collections, size classes, safe area, keyboard and appearance
- 7.8 · Keyboard shortcuts, pointer, Apple Pencil and multitasking
- 7.9 · Hosting SwiftUI in UIKit and UIKit in SwiftUI
- 7.10 · Initialisers, stack views, scroll views and modern buttons
- 7.11 · Layout passes, retain cycles and menus
- 7.12 · Refreshing diffable cells, outlines and carousel layouts