Create a UIButton in Code with Objective-C

iPhone Button tutorial for Xcode

Create a UIButton Programmatically

When you need more control over the user interface buttons and layout you will need to learn how to create a UIButton in code. Creating a button in code enables dynamic button creation, where you can create buttons in response to panels sliding or context sensitive dialog messages. Understanding code allows you to create interactive and playful interfaces. 

Creating your first button in code can be challenging, you might find yourself in a situation where you don’t see your button. This is a common mistake for developers who are new to the way iOS works with UIView and UIViewController objects. 

There are 5 important steps that you need to follow when adding any kind of UIView, UIButton, or UILabel programmatically. If you do each of these steps, you will understand how to add any kind of user interface (UI) element to your app.

  1. Create a UIButton using the class method buttonWithType:
  2. You need to set text for the button for the current UIControlState.
  3. You need to set the size of the button. 
  4. You need to specify button’s position.
  5. You need to add the button to a visible parent view (i.e. self.view).

If you miss any of these steps, you’ll be staring at a blank screen. You won’t be able to see or touch your button.

Step 1: Create your First iOS 7 UIButton in Code

You can create your first iOS 7 button in code, it will look like the default iOS 7 text buttons using the standard tint color. Open the ViewController.m file and look for the viewDidLoad: method. Add the bold code below to create a button inside the curly braces.

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"Press Me" forState:UIControlStateNormal];
    [button sizeToFit];
    [self.view addSubview:button];
} 
The default position of a button in code is the top left corner.

The default position of a button in code is the top left corner.

Run the app, and tap the button. 

Did you notice the “Press Me” button is behind the status bar in the top left corner. Sometimes you can’t click the button because it’s behind the status bar. You can fix the bug by setting the center position.

Step 2: Set the Button's Center Position

You can set the center to a new (X, Y) point using the CGPointMake() function. On an iPhone 5 screen your display is 320 points wide and 536 points tall. To get the center X coordinate, divide 320 by 2. Next, use a positive Y value to shift the button downward, you can use 60.

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"Press Me" forState:UIControlStateNormal];
    [button sizeToFit];

    // Set a new (x,y) point for the button's center
    button.center = CGPointMake(320/2, 60);

    [self.view addSubview:button];
} 
Change the center position to move the button around your iPhone app.

Change the center position to move the button around your iPhone app.

Step 3: Add an action to the button

The button won’t do anything when you tap on it, until you add an action. Define a new method that can be called when the button is tapped. Add it below the viewDidLoad method.

- (void)buttonPressed:(UIButton *)button {
     NSLog(@"Button Pressed");
}

The method buttonPressed: will be called when the button is touched. To be specific it’s a touch inside the bounds of the button. Button presses can be canceled when you drag your finger outside the boundaries of a button, instead of lifting up inside the button. 

To test if it’s working add an NSLog() print statement to show a message on the Console.

You will add a Target/Action pair to the button to give it access to the code file that defines the method and behavior that you want to happen with a button tap. Use the @selector keyword to tell the button the name of the method, including the colon.

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"Press Me" forState:UIControlStateNormal];
    [button sizeToFit];
    button.center = CGPointMake(320/2, 60);

    // Add an action in current code file (i.e. target)
    [button addTarget:self action:@selector(buttonPressed:)
     forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button];
} 

Run the app and tap the button. Now you will see the message in the text Console on the bottom half of Xcode’s window.

The NSLog() function displays text in the Console panel in Xcode.

The NSLog() function displays text in the Console panel in Xcode.

More iPhone Button Customization

You can change the font, text color, and background images for any button on iOS. If you want to learn more, sign up for the iPhone mailing list.

 
Subscribe and you will get FREE access to a 5 video course on custom buttons for iOS.

Subscribe and you will get FREE access to a 5 video course on custom buttons for iOS.

 



You can save so much time using this skill...

There is one thing that I don't teach. I don't teach it because I'm not an expert, but I have a friend, Maxime, who does teach it.

Learning to code is just part of the puzzle when you make an iPhone app. 

If you approach app development without any foundation in design, then you can waste a ton of time and money building the wrong app.

After talking with Maxime, he agreed to provide a great deal on his comprehensive course. Maxime teaches the best-selling course called Mobile App Design from Scratch

If you're developing a mobile app, you need to understand how to design it, and Maxime's class is a great foundation. His course will teach you a complete workflow that will take you from your idea to a fully designed app ready to be coded. 

He'll teach you how to use fantastic design software (not Photoshop!) and all the design concepts you need to know. 

Click here to use the coupon: https://www.udemy.com/mobile-app-design-from-scratch/?couponCode=ProgrammIphoneApp50

I'll be honest...

I don't promote things that I don't love. 

I LOVE the design tool that Maxime teaches. You can learn about it in his complete design course.

It has been a HUGE time saver in the production of my apps and games and I know that you will appreciate it as much as I have. 

Signup today with this limited discount and you will save time! https://www.udemy.com/mobile-app-design-from-scratch/?couponCode=ProgrammIphoneApp50

Make Your iPhone App Personalized with Custom Messages

Bomb Dodge game over screen with a custom message and stats.

Bomb Dodge game over screen with a custom message and stats.

We want people to enjoy using the app. Instead of displaying the same message over and over again you can make it customized. Create a set of expressions or messages that you want the user to share on social networks or when they brag about an achievement in your game, or how helpful the app was in saving time or reducing complexity. 

I use these custom messages in Bomb Dodge (free on the App Store). Download it and try pressing the Twitter or Facebook buttons after you explode. You can also see custom messages that we display after each game to give the death screen a bit more character.

Code

At the top of your ViewController you'll want to connect a UILabel and a UIButton to your code. This connection can be made quickly with the Assistant Editor and the right-click and drag method. After you do that you'll need an array to store values from the text file. Use NSArray instead of NSMutableArray because you won't need to change it after you load it from disk.

#import "ViewController.h"

@interface ViewController () {
    NSArray *_socialMessages;
}
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _socialMessages = [[NSMutableArray alloc] init];
}

The code is straight forward, you'll just need a text file with messages separated by a return (newline). NSString has a convenient method to load a text file into a string using it's file path. You can separate each message and create an array using the componentsSeparatedByString: method using the newline character @"\n".

- (void)loadSocialMessages {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"socialMessages.txt" ofType:nil];
    NSError *error = nil;
    NSString *fileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
    if(error) {
        NSLog(@"Unable to load social messages: %@", [error localizedDescription]);
    }
    _socialMessages = [fileContents componentsSeparatedByString:@"\n"];
}

Now that you can load messages it would help to have a text file. Go to Xcode > File > New > File. Select Other on iOS > Empty. 

Choose iOS > Other > Empty to create a .txt file.

Choose iOS > Other > Empty to create a .txt file.

After you create it you'll want to save it as a .txt file type.

Save the file as a .txt file so that we can load it into our iPhone app.

Save the file as a .txt file so that we can load it into our iPhone app.

Add some funny messages or serious messages that might be useful for a user.

Are you ready to explode? 
Bet you can't beat my score!
Bomb Dodge is awesome, you can smash bombs!
Bomb Dodge is so much FUN!
Bombee is so cute! He died, so I'll have to try better next time.
Boom goes the dynamite!
BOOM! My fuse ran out in Bomb Dodge ... can you can do better?
Can you outlast me in Bomb Dodge?
Click Like to save lives!
Do the exact opposite of what a bomb is supposed to do in Bomb Dodge!
Don't explode, stay alive!!!
Don't let me explode in Bomb Dodge!
Don't mix fire and explosives.
Download Bomb Dodge and don't explode!
Endless runner meets bomb defense game. Don't blow up!

In your viewDidLoad: method you should add the method call to loadSocialMessages below where you create the array.

_socialMessages = [[NSMutableArray alloc] init];
[self loadSocialMessages];

To get a message you'll use the arc4random_uniform(10) function that returns a number, for example between 0-9. You can use the array.count to get the total number of messages and then choose one. After you implement that method you can connect our nextButton to pull a random message and display it in your text field.

- (NSString *)randomSocialMessage {
    NSString *message = nil;
    if(_socialMessages.count > 0) {
        int messageIndex = arc4random_uniform([_socialMessages count]);
        message = _socialMessages[messageIndex];
    }
    return message;
}

- (IBAction)nextButtonPressed:(id)sender {

    self.messageLabel.text = [self randomSocialMessage];
}

Last but not least, you should make sure that when you run the app that it starts with a message. Grab a random message in the viewDidLoad: method and set it on the label.

- (void)viewDidLoad {
    [super viewDidLoad];

    _socialMessages = [[NSMutableArray alloc] init];
    [self loadSocialMessages];
    self.messageLabel.text = [self randomSocialMessage];
}

Checkout some screens where you can use the message on a share sheet for Facebook or Twitter. The Social.Framework makes it super easy to setup. 

Twitter Share Sheet on iOS

Twitter Share Sheet on iOS

Facebook Share Sheet on iOS - Look it's a different message every time!

Facebook Share Sheet on iOS - Look it's a different message every time!

Connect

  1. Download the sample Xcode project and make your apps more friendly or spunky!
  2. Email me a screenshot of how you use it in your app at
  3. Subscribe to my iPhone mailing list.