2.16. Adding Buttons to the User Interface with UIButton

Problem

You want to display a button on your UI and handle the touch events for that button.

Solution

Use the UIButton class.

Discussion

Buttons allow users to initiate an action in your apps. For instance, the iCloud Settings bundle in the Settings app presents a Delete Account button in Figure 2-52. If you press this button, the iCloud app will take action. The action depends on the app. Not all apps act the same when a Delete button is pressed by the user. Buttons can have images in them as well as text, as we will soon see.

A Delete Account button

Figure 2-52. A Delete Account button

A button can assign actions to different triggers. For instance, a button can fire one action when the user puts her finger down on the button and another action when she lifts her finger off the button. These become actions and the objects implementing the actions become targets. Let’s go ahead and define a button in our view controller’s header file:

#import <UIKit/UIKit.h>

@interface Adding_Buttons_to_the_User_Interface_with_UIButtonViewController
           : UIViewController

@property (nonatomic, strong) UIButton *myButton;

@end

Note

The default height of UIButton is 37.0f points.

The next step is to synthesize this property:

#import "Adding_Buttons_to_the_User_Interface_with_UIButtonViewController.h" @implementation Adding_Buttons_to_the_User_Interface_with_UIButtonViewController @synthesize ...

Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.