-
Notifications
You must be signed in to change notification settings - Fork 1
AA 1.21. Adding Buttons to the User Interface with UIButton
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 im‐ plementation file:
#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UIButton *myButton; @end
Next, we move on to the implementation of the button
- (void)viewDidLoad { [super viewDidLoad]; self.myButton = [UIButton buttonWithType:UIButtonTypeInfoLight]; self.myButton.frame = CGRectMake(110.0f, 200.0f, 100.0f, 44.0f); [self.myButton setTitle:@"Press Me" forState:UIControlStateNormal]; [self.myButton setTitle:@"I'm Pressed" forState:UIControlStateHighlighted]; [self.myButton addTarget:self action:@selector(buttonIsPressed:) forControlEvents:UIControlEventTouchDown]; [self.myButton addTarget:self action:@selector(buttonIsTapped:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:self.myButton]; // Do any additional setup after loading the view, typically from a nib. } - (void) buttonIsPressed:(UIButton *)paramSender{ NSLog(@"Button is pressed."); } - (void) buttonIsTapped:(UIButton *)paramSender{ NSLog(@"Button is tapped."); } @end
In this example code, we are using the setTitle:forState: method of our button to set two different titles for the button. The title is the text that gets displayed on the button. A button can be in different states at different times—such as normal and high‐ lighted (pressed down)—and can display a different title in each state. So in this case, when the user sees the button for the first time, he will read “Press Me.” Once he presses the button, the title of the button will change to “I’m Pressed.”
We did a similar thing with the actions that the button fires. We used the addTarget:ac tion:forControlEvents: method to specify two actions for our button:
-
An action to be fired when the user presses the button down.
-
Another action to be fired when the user has pressed the button and has lifted his finger off the button. This completes a touch-up-inside action.
The other thing that you need to know about UIButton is that it must always be assigned a type, which you do by initializing it with a call to the class method buttonWithType, as shown in the example code. As the parameter to this method, pass a value of type UIButtonType:
typedef NS_ENUM(NSInteger, UIButtonType) { UIButtonTypeCustom = 0, UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0), UIButtonTypeDetailDisclosure, UIButtonTypeInfoLight, UIButtonTypeInfoDark, UIButtonTypeContactAdd, UIButtonTypeRoundedRect = UIButtonTypeSystem, };