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.
The shortcut
Ask which way the arrow points: code → view (read or change it) is an outlet; view → code (the user did something) is an action.
The name field
Code must read its text when saving. Code → view → outlet
nameField.
The trap: renaming an outlet property in code without reconnecting it. The storyboard still looks for the old name, and the app crashes on load with a "not key value coding-compliant" error. Check the Connections inspector after renaming.
Drills
Answer fast — trust the rule.
Code needs to change a label's text. What connection does it need?
Why is an outlet usually declared weak?
You rename nameField to titleField in code only. What happens?
Which file holds one reusable view, such as a custom hike cell, on its own?
Remember
- Outlets let code reach the view; actions let the view call the code.
- Storyboards hold screens and segues; XIBs hold single views; Auto Layout constraints position them.
- Trap: renaming an outlet in code without reconnecting it crashes at load.
