Views and the View Hierarchy
Every pixel on TrailLog's hike card — the photo, the name, the distance, the star button — is drawn by a view. Views sit inside other views, like boxes inside boxes. Once you see that tree, layout and touch handling stop being mysterious.
The rule
Every screen is a tree of rectangles; each view lives in its parent's coordinates.
A UIView is a rectangle that draws content and can receive touches. UIKit's components are all views with extra skills:
UILabel— text.UIImageView— an image.UIStackView— arranges children in a row or column.UIButton,UISwitch,UITextField,UISlider— controls (subclasses ofUIControl) that report user actions.UITableViewandUICollectionView— scrolling lists and grids that reuse views as you scroll.
Views form a hierarchy. A view's children are its subviews; its parent is its superview. At the root is the app's UIWindow.
let card = UIView(frame: CGRect(x: 16, y: 100, width: 340, height: 120))
card.backgroundColor = .secondarySystemBackground
let nameLabel = UILabel(frame: CGRect(x: 12, y: 12, width: 200, height: 24))
nameLabel.text = "Ridge Loop"
card.addSubview(nameLabel) // nameLabel is now inside card
view.addSubview(card) // card is now inside the screen's root viewTwo rectangles describe every view:
frame— its position and size in its superview's coordinates.nameLabelsits 12 points from the card's top-left, not the screen's.bounds— its own rectangle in its own coordinates, usually starting at (0, 0).
Coordinates are in points, not pixels; iOS scales points to the screen's pixel density. The origin (0, 0) is the top-left, and y grows downwards.
Order matters: subviews added later are drawn on top of earlier ones. Moving, hiding or removing a parent does the same to all its children.
The shortcut
To find where a view appears on screen, walk up the tree adding frame origins until you reach the window.
Start at the label
nameLabel.frame.originis (12, 12) — relative tocard.
The trap is setting a child's frame as if it were in screen coordinates. It is always relative to its superview. (Most real layouts use Auto Layout constraints instead of fixed frames, but the tree and coordinate rules still apply.)
Drills
Answer fast — trust the rule.
A label's frame origin is (10, 20) inside a card whose frame origin is (16, 100). Where is the label's top-left in the card's superview?
Which rectangle describes a view in its own coordinate system?
Two subviews overlap. Which one is drawn on top?
The card view is hidden. What happens to its name label?
Remember
- Every screen is a tree of views; the window is the root, subviews sit inside superviews.
frameis in the parent's coordinates,boundsin the view's own; origin top-left, y downwards.- Shortcut: add frame origins up the tree to find a view's place on screen.
