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.