iOS Create Custom Buttons and Controls

Source

(c) 2012 kevin languedoc (klanguedoc)

The Cocoa Touch Framework encapsulates many different frameworks that when grouped together form the iOS SDK or Software Development Kit. One of the most used frameworks is the UIKit Framework because it controls every aspect of the UI or User Interface, which is the interaction with the user. Within this framework you will find the various controls or UIControls as they are formerly called. The SDK provides some basic controls like UIButtons and UITextField and UILabel amongst others. If you need other controls or you want to enhance these basic UIControls to better blend with your application requirements, then you will need to create these yourself. Fortunately the UIKit provides any classes, methods and properties to help you develop custom controls easily and to attach events to these controls.

This tutorial will show one way to create custom controls easily without a lot of complicated code. I will demonstrate how to enhance the basic UIButton by applying custom image to change the appearance of the UIButton. The second example will demonstrate how to create a custom button using custom images and attach event handlers to allow a user to interact with the button. Finally I will show you how to create and animate a custom slider. I know these already exist in the UIKit and are available from the object library but I want to show how to create and animate your own in case this requirement comes up in the course of the application development endeavours.

OK Button Skin for UIButton
OK Button Skin for UIButton | Source
Custom Buttons
Custom Buttons | Source
Bar for Slider
Bar for Slider | Source
Circle for slider
Circle for slider | Source

Buttons

The iOS SDK with its many frameworks like the Quartz 2d drawing framework and the Core Graphics framework provide all the APIs to create custom images directly through Objective-C. However I have always found this to be over kill. I suppose this would be great as a University project, but in the “real” world, like in a corporate setting ,you don’t always have the time to create these objects from scratch. You can either purchase custom icons from a reseller or you can create your own using Microsoft PowerPoint, or Adobe Illustrator or a drawing tool like GIMP which is as powerful as Illustrator and its completely free.

Anyway, the first example will be a skin for the UIButton that I will add to an iOS project later. For these examples I will use PowerPoint. To create the UIButton skin, I will use a simple circle shape. I will apply an aqua bevelled Quick Style and add a “OK” text as in the following image. I will name this skin round.png. I will add this image to the iOS project later and configure a UIButton in the Storyboard. Right click on the image and select “Save as Picture” from the context menu.

The next graphic will be a group of Preparation shapes from the Flowchart section of the Basic Shapes. I will apply a bevelling to both. I will apply an orange color to the first image and a lime green to the second.On the first image I will add the “Press ME” text and on the second “I was pressed”. Right click on each image in turn and select “Save as Picture”. Keep or select the png file type since this is the best for background transparency.

For the slider, I will add a line and change the weight to 8 pt. Then I will change the line fill to red.Then I will add another circle with a .38 x .38 inches (.9652 centimeters). I will change the color to red as well. Next I will save the line and the small circle as separate images since the line will be stationary while the circle will slide from left to right and back again with a user’s input.

iOS Project

This next part is to create a Single View iOS Application using the corresponding template. Make sure to select the Storyboard option. Once the project is created select the project root group in the project explorer and add a new group tilted “images”. Then right click on this new group and select the “Add files to...” menu command. Browse to the location where you save the images and select the all and click “Add” to add then them to the project. Elect to “Copy items...” option in the next popover to actually add the files to the project and not just references.

Then open the storyboard and add a UIButton and a UILabel from the available UIControls in the Object Library. Then select the UIButton and open the Attributes inspector and set the round.png image to the image attribute. Next open the header file by selecting the Editor assistant and then adding a connection (control+drag) to the header file. Change the connection type to IBAction and name the IBAction uiButton. Repeat this exercise by selecting the UILabel and ctrl+dragging a connection for an IBOutlet to the header file. Name this connection textOutput.

Finally open the implementation file and locate the new IBAction method that was just created. In the the body add the code to write “I pressed the UIButton” as in the code listing below.

ViewController.h

//
//  ViewController.h
//  CustomButtons
//
//  Created by Kevin Languedoc on 12/30/12.
//  Copyright (c) 2012 Kevin Languedoc. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
@property(strong, nonatomic) UIButton *customBtn;
- (IBAction)uiButton:(id)sender;

@property (strong, nonatomic) IBOutlet UILabel *textOutput;


-(void)buttonPressed:(id)sender;
@end

ViewController.m

//
//  ViewController.m
//  CustomButtons
//
//  Created by Kevin Languedoc on 12/30/12.
//  Copyright (c) 2012 Kevin Languedoc. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize customBtn;

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

-(void) viewDidAppear:(BOOL)animated{
    customBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 125, 75)];
    [customBtn setBackgroundImage:[UIImage imageNamed:@"pressme.png"] forState:UIControlStateNormal];      [customBtn setBackgroundImage:[UIImage imageNamed:@"iwaspressed.png"] forState:UIControlStateHighlighted];
    [customBtn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:customBtn];

}

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

- (IBAction)uiButton:(id)sender {
    self.textOutput.text=@"I pressed the UIButton";
}


-(void)buttonPressed:(id)sender{
    self.textOutput.text=@"I pressed the Custom Button";
}
@end

Compile and run the app. Click on the round skinned UIButton and check the output. You should have the same output as in the following screenshots.

Skinned UIButton
Skinned UIButton | Source
Skinned button Pressed
Skinned button Pressed | Source

Custom Buttons

For the custom buttons, I start by adding a UIButton property to the header. Refer to the code listing above for the proper syntax. I also add a custom sender method called buttonPressed. The code is provided above in the listing for the header file.

In the implementation, I synthesize the customBtn property and add the viewDidAppear UIViewController method. In this method initialize the customBtn object and the set its size and location to 0,0, 125, 75 (x, y, width and height respectfully). Next add the background images for the normal state and the highlighted states and then add method target, buttonPressed, for the UIControlEventTouchUpInside event. finally add the custom button to the UIView as a subview.

If you compile and run this app again, the new button will appear in the top left corner of the app. If you click on the button the background will change to the “I was pressed” and the label output is “I pressed the Custom Button”.

Custom Button at Normal State
Custom Button at Normal State | Source
Custom Button at Highlighted State
Custom Button at Highlighted State | Source

Custom Slider

To create the custom slider I will add yet two more UIButtons called customSliderBar and customSliderCircle and a sender method called sliderAction in the header. To implement the slider, I add the bar.png and smallcircle.png images to the images group and initialize the bar customSliderBar button in the viewDidAppear method, setting the location and size to: 10, 122, 285, 9. Then set the background image to bar.png for the Normal state is the bar will be static and add the bar button to the view as a subview. You can run the app to check to see if the bar is displaying properly and at the proper location.

Repeat the same process for the small circle image which will be assigned to the customSliderCircle button. In addition you will need to set the sliderAction action target for the UIControlEventTouchDragInside drag event. In the sliderAction method create a CGPoint with the location of the small circle in the view. From this CGPoint set the x coordinate as a CGFloat, the y coordinate is static at 122. Then create a new CGPoint using the x and y coordinates and then assign the new CGPoint, newX, to the UIButton customSliderCircle.

The code additions are provided below:

ViewController.h Additions

...header additions

@property(strong, nonatomic) UIButton *customSliderBar;
@property(strong, nonatomic) UIButton *customSliderCircle;
- (IBAction)uiButton:(id)sender;

@property (strong, nonatomic) IBOutlet UILabel *textOutput;


-(void)buttonPressed:(id)sender;
-(IBAction)sliderAction:(UIButton*)sender withEvent:(UIEvent *) event;

ViewController.m Additions for Custom Slider

-(void) viewDidAppear:(BOOL)animated{
    ...
    
    //custom slider
    customSliderBar = [[UIButton alloc] initWithFrame:CGRectMake(10, 125, 285, 9)];
    [customSliderBar setBackgroundImage:[UIImage imageNamed:@"bar.png"] forState:UIControlStateNormal];      
    [self.view addSubview:customSliderBar];
    
    customSliderCircle = [[UIButton alloc] initWithFrame:CGRectMake(10, 122, 15, 15)];
    [customSliderCircle setBackgroundImage:[UIImage imageNamed:@"smallcircle.png"] forState:UIControlStateNormal];
    [customSliderCircle addTarget:self action:@selector(sliderAction:withEvent:) forControlEvents:UIControlEventTouchDragInside];
    [self.view addSubview:customSliderCircle];

}

-(IBAction)sliderAction:(id)sender withEvent:(UIEvent *) event{
    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];
    CGFloat x = point.x;
    CGFloat y = 122;
    UIControl *control = sender;
    CGPoint newX = CGPointMake(x, y);
    control.center = newX;
}

I hope this help you create your custom controls using a combination of custom images and a bit of Objective-C and the UIKit and Foundation classes.

More by this Author


Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working