iOS Programming Recipe 1: Controlling Actions With Buttons

This Recipe is going to cover the UIButton and a few ways that we can work with it.

Assumptions

Uses

There are a few things we can do with buttons, but the main reason you would want a button is to either enter a value or trigger an action. In some cases, you may want to have the button change it’s properties based on some state in your app.

Adding a UIButton using the interface builder

From the Object library located in the Utility bar on the bottom right find the “Round Rectangular Button” . Click the Button object and drag it onto your view. Whew! that was easy!  Since were already in the interface builder, go ahead and click and drag a label onto the view as well.

Your view should look something like this:

To change the text value of the button go ahead and double click it. Rename the button to “Button 1”

Making the Connections

Now that we’ve designed the interface(although it’s kind of ugly), it’s time to make the connections. Change your view to the assitant editor view and control click and drag the button into the .h file between @interface and @end.

Click to view larger

When prompted, go ahead and change the connection to action and give it a name of “calculate”. We give the button an action type connection because we want the button to execute an action when pressed.

Now control click and drag the label into the .h file between the @interface and @end tags as well. This time make the connection type outlet and the name “sum”.

Now we’ll need to give the button something to calculate.  For Now we’ll just make the button add two numbers.  Let’s say 1 and 2.

Adding the Code

Switch the editor view back to the standard editor and select the viewController.m. You’ll want to edit the ViewController.m as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize sum;

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (IBAction)calculate:(id)sender {

int addedNumbers;

addedNumbers = 1 + 2;
NSLog(@"The Sum of 1 + 2 is %d",addedNumbers);
self.sum.text = [NSString stringWithFormat:@"%i",addedNumbers];
}

@end

On line 8 we synthesize our sum label. this sets up the setter and getter for us so we can use the dot notation to change the text of the label.

On line 25 we’re creating a primitive integer variable to store our calculation.
On line 27 we are adding 1 and 2 together and storing them into our primitive integer variable.
On Line 28 we are using NSLog to output the formatted text “The Sum of 1 + 2 is 3 ” in our debugging output window. Notice the 3 in this value is calculated.
On line 29 we are Calling a method from the NSString object to give us the string value of our calculated number and then set the text of the label sum to that value.

Go Ahead and press play to simulated the App. You should see this!

When you press the Calculate button you will see the printout “The Sum of 1 + 2 is 3 ” in our debugger output. And the Label will also change from the text “Label” to “3”. Pretty neat huh?

Getting a Value From a Button

Alright, So far we’ve added a button and called an action that adds the numbers 1 and 2 together when the button is pressed. What if we have more than one button, and we want to know which one was pressed? Now we’ll tackle that case.

Start off by adding another button next to Button 1 and change the text to “Button 2”. Go Ahead and make your Label wider , center it, and set the text to “No Button Pressed” . Your view should now look like this

Underneath the view area of the Attributes Inspector. Change the Tag for Button 1 to ‘1’ and the Tag for Button 2 to ‘2’. These values will let us know what button was pressed.

Now Control Click and Drag button two onto the calculate action in the viewController.h file. This will tie the new button to the same action as the first button we created.

 

 

click to view larger

 

Now we’ll go modify the viewController.m file and change the code a bit. Our App will no longer add two numbers, it will just let us know what button we pressed. Therefore, we’re wiping out all of the code in the calculate action(method).

Your viewController.m file should now look like this:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize sum;

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (IBAction)calculate:(id)sender {

if([sender tag] == 1){

self.sum.text = @"You Pressed Button 1";

}
else if([sender tag] == 2){

self.sum.text = @"You Pressed Button 2";

}
else{
self.sum.text = @"no button pressed";
}
}

@end

Now You’ll see the only things I have changed are the lines inside the calculate action. These lines are just a conditional statement that checks to see what the tag value was of the last button pressed. Go Ahead and simulate and you will see the text change when each button is pressed.

Now that we’ve pretty much changed the functionality from our starting point, the Property “sum” and Method “calculate” don’t make a whole lot of sense. Obviously It’s a better practice to change these to something more descriptive to what we are doing. We can go ahead and do this, but this will most likely throw some errors if we don’t go fix the connections. For this reason, I didn’t bother.  If we were to change these values throughout the code there would be no error but it would crash when  we try to simulate. This is because the a connection still exists. If you see an error like the one in the screenshot below. It usually means you deleted or renamed something that still has a connection.

 

That’s It! Not to bad. Soon We’ll do a post on Button Styling and Customization.

About Joe Hoffman

I am An Electrical Engineer that spends a lot of my off time doing web development and other programming. Currently I am trying to expand my knowledge with iOS and I find that writing tutorials helps me learn more thoroughly as well as provide some useful info to others.

Comments

  1. Hi, Thank you for posting these tutorials. I have a question about creating the button action. It says here to control drag the button into the .h file but in the “Your First iOS App” tutorial they have you control drag the button into the .m file. Is the only difference that when you add the action to the .h file it’s made public and in the .m file it’s private? Again thank you for your time!

    • Joe Hoffman says:

      Hi Brian!

      The concept of private and public is a bit weird in Objective – C. It’s not so much Private as it is unlisted. You can think of the header file as a table of contents. Without the table of contents, other classes can’t find your property or method. Also, without the table of contents it’s more difficult for people to know what’s in a class. So if you have properties or methods only in the .m file then it’s only visible to the class it’s defined in. If you define them in .h file everyone can see them. I typically like to add the main functionality of a class to the header so I can easily look at it and tell what that class can do and what properties are available.

Speak Your Mind

*

css.php
Privacy Policy