Storyboards, Outlets and Actions
TrailLog's "New Hike" screen has a name field, a distance slider and a Save button. You can build it in code, or draw it visually in Interface Builder and connect it to code. Either way, two connections do all the work: one lets code reach a view, the other lets a view call code.
The rule
Outlets let code reach the view; actions let the view call the code.
Interface Builder is Xcode's visual editor. It edits two kinds of file:
- Storyboards (
.storyboard) — several screens (scenes) and the transitions between them (segues) in one file. - XIBs (
.xib) — a single view or cell, loaded on its own; handy for reusable pieces.
Both are XML that UIKit loads at runtime to create real view objects.
An outlet is a property that the storyboard fills in with a view it created:
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var distanceSlider: UISlider!It is weak because the view hierarchy already owns the view, and implicitly unwrapped (!) because it is nil until the storyboard loads, then always set.
An action is a method the storyboard calls when a control sends an event, such as a button's Touch Up Inside:
@IBAction func saveTapped(_ sender: UIButton) {
let hike = Hike(name: nameField.text ?? "", distanceKm: Double(distanceSlider.value))
store.add(hike)
}To connect them, open the storyboard with the view controller's code in the assistant editor, then Control-drag from the view into the code. Dragging onto a property line connects an outlet; choosing Action creates a method.
Views in a storyboard are positioned with Auto Layout constraints — rules such as "16 points from the leading edge" or "centred horizontally". Each view needs enough constraints to fix its position and size, or Interface Builder shows red and orange warnings.