ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Computer Programming Tutorials

iOS Create Custom Buttons and Controls

Updated on December 30, 2012
klanguedoc profile image

Kevin is Software Developer with 20 years experience designing and building software applications including iOS and Android apps.

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.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)