Run your app in Simulator to make sure that the UI elements
you added look the way you expect them to. If you click the Hello
button, it should highlight, and if you click inside the text field, the
keyboard should appear. At the moment, though, the button doesn’t do
anything, the label just displays “Label,” and there’s no way to dismiss
the keyboard after it appears. To add the functionality you want, you
need to make the appropriate connections between the UI elements and the
view controller. These connections are described next.
Create an Action for the Button
When the user activates a UI element, the element can send an action message to an object that knows how to perform the corresponding action method (such as “add this contact to the user’s list of contacts”). This interaction is part of the target-action mechanism, which is another Cocoa Touch design pattern.In this tutorial, when the user taps the Hello button, you want it to send a “change the greeting” message (the action) to the view controller (the target). This message changes the string (that is, the model object) that the view controller manages. Then, the view controller updates the text that’s displayed in the label to reflect the change in the model object’s value.
Using Xcode, you can add an action to a UI element and set up its corresponding action method by Control-dragging from the element on the canvas to the appropriate source file (typically, a view controller’s source file). The storyboard archives the connections that you create in this way. Later, when the app loads the storyboard, the connections are restored.
When you Control-dragged from the Hello button to the
HelloWorldViewController.h
file and configured the resulting action, you accomplished two things:- You added the appropriate code to the view controller class. Specifically, you added the following action method declaration to
HelloWorldViewController.h
:
- (IBAction)changeGreeting:(id)sender;
HelloWorldViewController.m
:
- (IBAction)changeGreeting:(id)sender {
}
- You created a connection between the button and the view controller.
No comments:
Post a Comment