iPhone Tutorial - Creating Basic Buttons

Skill

iPhone Tutorial - Creating Basic Buttons

Posted in:

In our previous introductory tutorial on iPhone development, a question was asked about how to create a button and listen for its UIControlEventTouchUpInside event. I didn't want to put everything that was required into the comments of that post, so I created this tutorial as an answer. Much like the last tutorial, I'm still avoiding Interface Builder and am going to build the button using nothing but code.

I'm going to use the code created from the last tutorial as a starting point, so I would recommend checking that one out if you're new to iPhone development. Basically what we're starting with is a new Window-Based application with one UIViewController subclass. We've implement the loadView function, which basically gives us total control over populating the view controller with our views. Here's the code that's needed before we can begin with our button.

// Implement loadView to create a view hierarchy programmatically,
// without using a nib.
- (void)loadView {
       
  //allocate the view
  self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
       
  //set the view's background color
  self.view.backgroundColor = [UIColor whiteColor];
}

All we're doing here is creating the UIViewController's view object, setting its size to the entire screen, and making its background white. This is slightly different from the last tutorial since I no longer have to hardcode the size of the view. The UIScreen class has a class method, mainScreen, which we can use to get the screen of the device. We can then ask that object for its applicationFrame, which will be the total size of the iPhone's display.

All right, now let's get the basic stuff out of the way. Here's the code required to create the button and give it some text.

// Implement loadView to create a view hierarchy programmatically,
// without using a nib.
- (void)loadView {
       
  //allocate the view
  self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
       
  //set the view's background color
  self.view.backgroundColor = [UIColor whiteColor];
 
  //create the button
  UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
       
  //set the position of the button
  button.frame = CGRectMake(100, 170, 100, 30);
 
  //set the button's title
  [button setTitle:@"Click Me!" forState:UIControlStateNormal];
 
  //add the button to the view
  [self.view addSubview:button];
}

The first thing we need to do is create a button. The UIButton object has a class method called buttonWithType that automatically creates buttons with various types. We just want a regular old button so I passed in UIButtonTypeRoundedRect. Next up, we need to position and size the button, so I set the frame property to my specified bounds. A button's not much use without text, and setTitle is used to set it. You can specify a different title for each state, and if a title is not set for a specific state, it will use whatever was set for UIControlStateNormal. That's why it's the only state we're setting a title for. All that's left now is to add it as a subview to the UIViewController's view object. If you were to compile and run the code you'd see a button in the center of the screen.

iPhone Button Screenshot

A button doesn't do us a lot of good unless we know when it's been pressed. The next thing we need to add is a hook to listen for when the user clicks it.

// Implement loadView to create a view hierarchy programmatically,
// without using a nib.
- (void)loadView {
       
  //allocate the view
  self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
       
  //set the view's background color
  self.view.backgroundColor = [UIColor whiteColor];
 
  //create the button
  UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
       
  //set the position of the button
  button.frame = CGRectMake(100, 170, 100, 30);
 
  //set the button's title
  [button setTitle:@"Click Me!" forState:UIControlStateNormal];
 
  //listen for clicks
  [button addTarget:self action:@selector(buttonPressed)
   forControlEvents:UIControlEventTouchUpInside];
 
  //add the button to the view
  [self.view addSubview:button];
}

-(void)buttonPressed {
  NSLog(@"Button Pressed!");
}

We use the addTarget function to hook into the UIControlEventTouchUpInside event. Basically, what we're saying here is to send that event to self and call the function buttonPressed. The @selector directive returns what's essentially a function pointer in the Objective C world. Lastly, if we're telling the button to send a message to a class, we had better implement a method for that message, so all we do is simply log a message to the console. You can view the console by selecting Run / Console on XCode's menu.

That's it! Now you've got a button and you know when the user has clicked it. If you've got questions or comments feel free to leave them below or check out the forums.

huggie
06/07/2009 - 01:35

Nice tutorial, thanks. So how is everything hooked when one use the interface builder? Presumably the auto-generated codes goes to the xib files directly, but it seems like there is no explicit reference to the xib file in the delegate nor the controller code.

reply

Amir
11/05/2009 - 13:59

thanks for this great tutorial! one question though: why when I try to release the button in the end of the function it ruin the program? is what sense button different from label?

reply

Anonymous
11/17/2009 - 16:17

Amir, you don't need to release the button because you create it with the buttonWithType: method, which is a factory method and thus returns an autoreleased object. I suppose you create your UILabel using alloc, which is why you have to explicitly release it when you're done with it.

reply

Lite
11/19/2009 - 10:10

Very good for beginners. Got me started. Other documentation i found so far always got me stuck in details that were too advanced.

reply

natedog
01/03/2010 - 13:51

I had a problem in the - (void)loadView { part
Please Help.

reply

The Reddest
01/04/2010 - 12:07

Do you have any details?

reply

blindgoat
01/06/2010 - 01:29

Great starter tutorial. I don't know why there are so few people wanting to write programs without IB. Thank you :)

I'm trying to make a custom subView (I think) that is essentially this:

A square that is all clickable with a UILabel on top of it. I want to be able to place any picture I want on the background of the "button" square.

I want to be able to create as many instances of this as I want on screen and position them.

Do you have any hints for how I would go about doing this? You can email be at blindgoat AT g mail DOT COM

Thanks so much!
blindgoat

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.

Sponsors