- 3.1 Introduction
- 3.2 Technologies Overview
- 3.3 Building the App's UI
- 3.4 Creating Outlets with Interface Builder
- 3.5 Creating Actions with Interface Builder
- 3.6 Class <tt>ViewController</tt>
- 3.7 Wrap-Up
3.5 Creating Actions with Interface Builder
Now that you’ve created the outlets, you need to create actions (i.e., event handlers) that can respond to the user-interface events. A Text Field’s Editing Changed event occurs every time the user changes the Text Field’s contents. If you connect an action to the Text Field for this event, the Text Field will send a message to the view-controller object to execute the action each time the event occurs. Similarly, the Value Changed event repeatedly occurs for a Slider as the user moves the thumb. If you connect an action method to the Slider for this event, the Slider will send a message to the view controller to execute the action each time the event occurs.
In this app, you’ll create one action method that’s called for each of these events. You’ll connect the Text Field and the Slider to this action using the Assistant editor. To do so, perform the following steps:
Control drag from the Text Field in the scene to ViewController.swift between the right braces (}) at lines 25 and 26 (Fig. 3.37), then release. This displays a popover for configuring an outlet. From the Connection list in the popover, select Action to display the options for configuring an action (Fig. 3.38).
Fig. 3.37 | Control dragging to create an action for the Text Field.
Fig. 3.38 | Popover for configuring an action.
- In the popover, specify calculateTip for the action’s Name, select Editing Changed for the Event and click Connect.
Xcode inserts the following empty method definition in the code:
@IBAction func calculateTip(sender: AnyObject) {
}
and displays a small bullseye () symbol (Fig. 3.39) in the gray margin to the left of the method indicating that the action is connected to a UI component. Now, when the user edits the Text Field, a message will be sent to the ViewController object to execute calculateTip. You’ll define the logic for this method in Section 3.6.6.
Fig. 3.39 | Control dragging to connect an existing @IBAction to the Slider.
Connecting the Slider to Method calculateTip
Recall that calculateTip should also be called as the user changes the custom tip percentage. You can simply connect the Slider to this existing action to handle the Slider’s Value Changed event. To do so, select the Slider in the scene, then hold the control key and drag from the Slider to the calculateTip: method (Fig. 3.39) and release. This connects the Slider’s Value Changed event to the action. You’re now ready to implement the app’s logic.