Posts tagged #uibutton

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 and 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 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.

 



Posted on August 5, 2014 and filed under Programming .

Programmatic UIButton on iOS 7.0 - Create a UIButton with Code

Create UIButton in code

Create UIButton in code

1. Update (September 8th, 2014): Start learning Swift for iOS 8 with a new tutorial series using Xcode 6. [Click here to read about Swift 101]

2. New UIButton Tutorial (September 8th, 2014): Read and watch a tutorial series on how to create UIButton's in code.

Earlier I posted on how to customize UIToolbar buttons and UINavigationBar buttons (UIBarButtonItem). The tutorial was released before iOS 7.0, when Apple nixed the idea of having a graphical element around buttons.

If you're working on a game or want to still add a little embellishment (like me) then you're going to need to learn how to wrangle buttons on iOS 7.0. Adding buttons to the Interface Builder is easy, but when you first try to create a UIButton in code it's challenging. There's some hidden steps, or steps you might forget after you get accustomed to Auto Layout.

There's really three options for creating the UIButton. You can create the standard iOS 7 button, a modified iOS 7 button, or a custom button (more work). Apple recommends that you don't add subviews to the UIButton, but it is possible, and it's something we're doing in .

Each UIButton behaves differently when you tap it. Notice the tint color changes on the top.

Each UIButton behaves differently when you tap it. Notice the tint color changes on the top.

 

Programmatically Create a Standard iOS 7.0 UIButton

1. Create a button of UIButtonTypeRoundedRect and add it to the subview.

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.view addSubview:button];

2. You'll need to set the title for a UIControlStateNormal, otherwise you won't see any text. UIButton's are different than UILabel, we can't just set the text property

[button setTitle:@"Press Me" forState:UIControlStateNormal];

3. Ask the button to resize itself because it's currently a 0 width and 0 height button. We won't see it!

[button sizeToFit];

4. Give the button an initial placement position. Otherwise it'll be in the top left corner.

button.center = CGPointMake(100, 50);

Programmatically Create a Custom iOS 7.0 UIButton

I like to use background images to give my UIButton objects a bit more spunk. This works well, especially in games where you don't need to follow all of the iOS 7.0 guidelines. However, I do like to create a button that behaves like an iOS 7.0 button when it's tapped. You can get all the behavior if you use the UIButtonTypeRoundedRect with a background image. When the button is pressed, the title and the background will fade out.

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.view addSubview:button];
[button setTitle:@"Hello" forState:UIControlStateNormal];


We need to use UIEdgeInsets to create more space between the title text and the sides of the UIButton. On iOS 7.0 these buttons have no side space. We'll create the edge inset with 6 points on the left and right side, and two points on the top side.

[button setContentEdgeInsets:UIEdgeInsetsMake(2, 6, 2, 6)];
[button sizeToFit];
button.center = CGPointMake(200, 50);

We want to have variable width buttons (depending on the text), so we'll create a resizable UIImage. In PhotoShop you'll want to create a square image with the height you'll use in the app.

Note: I used 40x40 in this example for the retina size (i.e. ) I don't bother adding the non-retina version to my projects since Xcode will auto generate it, if it's needed.

When we create stretchable images we'll need to use the point system (not pixels). So that's essentially the non-retina size, which would be 20x20 points. We need this size, because our UIEdgeInsets will be based on the point system. The image can stretch horizontally, so we'll use half the width and height to get the center pixel of our image to stretch. 20/2 = 10. That means on the top, left, bottom, and right sides we'll use 10 points.

[button setBackgroundImage:[[UIImage imageNamed:@"Button.png"] 
  resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)] 
  forState:UIControlStateNormal];

Programmatically Make a Custom UIButton

The last type of button is totally custom, but it's going to take a lot more work to make it feel like a button. You'll need to add background images or you'll never see it press anything. You'll also need to update the text color and font and handle transitions between different press states.

UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.view addSubview:customButton];

[customButton setTitle:@"Hello" forState:UIControlStateNormal];
[customButton setContentEdgeInsets:UIEdgeInsetsMake(0, 4, 0, 4)];
[customButton sizeToFit];
customButton.center = CGPointMake(200, 100 + 50 * i);

[customButton setBackgroundImage:[[UIImage imageNamed:@"Button.png"] 
  resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)] 
  forState:UIControlStateNormal];

[customButton setBackgroundImage:[[UIImage imageNamed:@"ButtonHighlighted.png"] 
  resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)] 
  forState:UIControlStateHighlighted];

[customButton setTitleColor:[UIColor blueColor] 
  forState:UIControlStateNormal];

Learn More

Signup for complete iPhone courses that provide structured learning and cover everything you need to know to make iPhone apps.

iPhone App Courses Gold Subscription


Wrap-up

  1. Download the sample project and replace the image assets with your artwork.
  2. Subscribe to my iPhone newsletter.
  3. Checkout my beginner iPhone development course on Skillshare.
Posted on January 22, 2014 and filed under Programming .