Create Radio Buttons and Checkboxes for iOS Applications

Updated on November 29, 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 iOS SDK and Xcode offers the basics in terms of UI controls. Two of the most used UI controls are checkboxes and radio buttons which are sorely lacking in the UIControls that comes with the iOS SDK. Fortunately the Cocoa Touch framework offers some excellent enclosed APIs provide the functionality needed to create checkboxes and radio buttons quickly.

This tutorial will show you with little code how to practically create checkboxes and radio buttons. Although very feasible to create completely in code, I will be using pre defined images of the checkboxes and radio buttons which are extremely easy to make with an assortment of graphic tools. In any software application or web applications in production, developers will include icons and images to help them create the look and feel that is required. So it makes common sense to use images to mimic the checkboxes and radio buttons in an iOS software application.

Radio buttons and Checkboxes
Radio buttons and Checkboxes | Source

Create Images

Before getting to the application which will only require minute coding, I would like to show how to style some checkboxes and radio buttons. For this example I will be using Powerpoint but the same effect can be achieved with variety of graphic tools which can include Apple’s Keynote or Google’s Presentation or Drawing. There is also Open Office that can be used or Gimp to name a few.

The first part of create a checkbox is to draw two squares. This is easy in Powerpoint. Add two square shapes to a blank slide. Format them as you wish but in one of them add two lines criss crossed like in the following screenshot. Right click on each image or shape and select “Save as Image” which will allow you to save these images as a png file.

Likewise for the radio buttons, first draw a circle, about .38 inches in diameter. Then draw a second circle shape inside the first making sure that the second circle is well centered within the first. Format the circles are you like to blend with your app. Next select the first two and right click on the two images and select “Grouping” from the context menu and “Group” to group these two images together to form a cohesive image. Then make a copy of this new image. In the second image, select the inner circle and change the fill to black or some other dark color. Finally save the two radio buttons as before to the file system. I have provide a screenshot of my radio buttons but you can make yours that best suits your needs.

Build the Application

Create a Single View iOS (iPhone) application. Once the project is setup, select the project root group and add a new group by right clicking on this project node and selecting new group. Name it Images. Then Right click on this new group and select “Add Files to ….” command and browse to the directory where you save your checkbox and radio button images. Click “Add” to copy them to the project.

ViewController Header
In the header file of the ViewController custom class add three UIButton instance variables: checkbox, radiobutton1 and radiobutton2 as in the source code listing below. These will be the checkbox and radio buttons in our scene later. Also add two instance methods: checkboxSelected and radiobuttonSelected. I will explain these in the implementation file.

ViewController.h

//
//  ViewController.h
//  RadioButtonsAndCheckbox
//
//  Created by Kevin Languedoc on 11/1/12.
//  Copyright (c) 2012 Kevin Languedoc. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property(strong, nonatomic) UIButton *checkbox;
@property(strong, nonatomic) UIButton *radiobutton1;
@property(strong, nonatomic) UIButton *radiobutton2;


-(void)checkboxSelected:(id)sender;
-(void)radiobuttonSelected:(id)sender;

@end

ViewController Implementation

viewDidAppear - Checkboxes

First synthesize the variables using the @synthesize directive. This is the same as creating gettter and setters. You can also assign a new name to the variable if you like as :

@synthesize checkbox = __checkbox;

However for this project I am performing a simple synthesis. Next I would like to draw your attention to the viewDidAppear method in the ViewController.m code listing below, which doesn’t in the default implementation but is a standard instance method in the UIViewController class. So add it here as in the ViewController.m code listing below as previously cited. In this method we are going to initialize the checkbox UIButton using the initWithFrame property. This property takes a CGRectMake object as input. As you may know the CGRectMake object has four parameters: x, y, width and height. I will set these parameters to 0, 0, 75, 75 respectively. This will place the button in the top left corner of the scene and make the button square with a size of 75x75 pixels. Remember users need to be able to use their fingers to select these buttons.

Next we will assign the checkbox images: CheckboxOff.png and CheckboxOn.png unless you named yours differently to the background and also define the which state the button must be at in order to set the background. For the “off” state, we will set the state to UIControlStateNormaland for the “on” set the state to UIControlStateSelected. The next line will set up the action events and what to do when the button is clicked. So add the addTarget with the @selector(checkboxSelected:) value. Remember to add the “:” colon at the end of the method name otherwise you will get a runtime error. The second parameter is the “forControlEvents” which event will trigger the action. In our case we will use the “UIControlEventTouchUpInside” which will trigger when the button is released.

All that is needed now is to add the button to the view which we will do with the addSubview property of the ViewController. Refer to the viewDidAppear method in the code listing below for a visual aid to this text.

ViewController.m - viewDidAppear For Checkboxes

-(void)viewDidAppear:(BOOL)animated{
    
    //Checkboxes
    
    checkbox = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 75, 75)];
    [checkbox setBackgroundImage:[UIImage imageNamed:@"CheckboxOff.png"] forState:UIControlStateNormal];
    [checkbox setBackgroundImage:[UIImage imageNamed:@"CheckboxOn.png"] forState:UIControlStateSelected];
    [checkbox addTarget:self action:@selector(checkboxSelected:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:checkbox];

However if you run the app now, you will CheckboxOff.png image but it won’t do anything because we still have to add the code to the checkboxSelected method. The method is quite simple. It checks to see if the button is selected using the sender argument and the isSelected property. If its selected then set the property to NO otherwise set it to YES. This will trigger the background images to switch from one to the other.

ViewController.m - checkboxSelected

-(void)checkboxSelected:(id)sender{

    
    if([checkbox isSelected]==YES)
    {
      [checkbox setSelected:NO];
    }
    else{
         [checkbox setSelected:YES];
    }
   
}

viewDidAppear - Radio Buttons

The radio buttons follow the same pattern with a few exceptions. First instead of one button, there are two but the code is identical except for the CGRectMake method. The first radio button has the following values: 0, 80, 75, 75. This means that the first radio button will placed next to the left edge of the scene but it will be 80 pixels from the top edge. the square will occupy the same space. The second radio button will have the following CGRectMake values: 80, 80, 75, 75. This means that set next to the first radio button and will occupy the same space. The other exception is that I added the tag property to the radio button UIButtons. We will use these in the radiobuttonSelected next.

Of course the value of the addTarget will be different since the buttons will call the radiobuttonSelected method when the radio buttons are touched. Add each radio button to the view with the addSubView property. Have a look at the provided code excerpt on the radio buttons to glean a better understanding on how to setup the code.

ViewController.m - viewDidAppear for Radio Buttons

  //radio buttons
    radiobutton1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 80, 75, 75)];
    [radiobutton1 setTag:0];
    [radiobutton1 setBackgroundImage:[UIImage imageNamed:@"RBOff.png"] forState:UIControlStateNormal];
    [radiobutton1 setBackgroundImage:[UIImage imageNamed:@"RBOn.png"] forState:UIControlStateSelected];
    [radiobutton1 addTarget:self action:@selector(radiobuttonSelected:) forControlEvents:UIControlEventTouchUpInside];
    
    radiobutton2 = [[UIButton alloc] initWithFrame:CGRectMake(80, 80, 75, 75)];
    [radiobutton2 setTag:1];
    [radiobutton2 setBackgroundImage:[UIImage imageNamed:@"RBOff.png"] forState:UIControlStateNormal];
    [radiobutton2 setBackgroundImage:[UIImage imageNamed:@"RBOn.png"] forState:UIControlStateSelected];
    [radiobutton2 addTarget:self action:@selector(radiobuttonSelected:) forControlEvents:UIControlEventTouchUpInside];

    
    [self.view addSubview:radiobutton1];
    [self.view addSubview:radiobutton2];

Finally lets look at the radiobuttonSelected method. It uses the sender’s tag value with the switch to determine which radio button is being pushed. Then it simply sets the isSelected property depending on which button is pushed, toggling from YES to NO and back again depending on the current value of the isSelected property.

The complete code is provided as always and play the included video to get a feel on how the code behaves at runtime. As you can see creating custom radio and checkboxes is very easy t do.

ViewController.m - radiobuttonSelected

-(void)radiobuttonSelected:(id)sender{
    switch ([sender tag]) {
        case 0:
            if([radiobutton1 isSelected]==YES)
            {
                [radiobutton1 setSelected:NO];
                [radiobutton2 setSelected:YES];
            }
            else{
                [radiobutton1 setSelected:YES];
                [radiobutton2 setSelected:NO];
            }

            break;
        case 1:
            if([radiobutton2 isSelected]==YES)
            {
                [radiobutton2 setSelected:NO];
                [radiobutton1 setSelected:YES];
            }
            else{
                [radiobutton2 setSelected:YES];
                [radiobutton1 setSelected:NO];
            }

            break;
        default:
            break;
    }
   
}

ViewController.m

//
//  ViewController.m
//  RadioButtonsAndCheckbox
//
//  Created by Kevin Languedoc on 11/1/12.
//  Copyright (c) 2012 Kevin Languedoc. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize checkbox, radiobutton1,radiobutton2;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}
-(void)viewDidAppear:(BOOL)animated{
    
    //Checkboxes
    
    checkbox = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 75, 75)];
    [checkbox setBackgroundImage:[UIImage imageNamed:@"CheckboxOff.png"] forState:UIControlStateNormal];
    [checkbox setBackgroundImage:[UIImage imageNamed:@"CheckboxOn.png"] forState:UIControlStateSelected];
    [checkbox addTarget:self action:@selector(checkboxSelected:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:checkbox];
    
    
    //radio buttons
    radiobutton1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 80, 75, 75)];
    [radiobutton1 setTag:0];
    [radiobutton1 setBackgroundImage:[UIImage imageNamed:@"RBOff.png"] forState:UIControlStateNormal];
    [radiobutton1 setBackgroundImage:[UIImage imageNamed:@"RBOn.png"] forState:UIControlStateSelected];
    [radiobutton1 addTarget:self action:@selector(radiobuttonSelected:) forControlEvents:UIControlEventTouchUpInside];
    
    radiobutton2 = [[UIButton alloc] initWithFrame:CGRectMake(80, 80, 75, 75)];
    [radiobutton2 setTag:1];
    [radiobutton2 setBackgroundImage:[UIImage imageNamed:@"RBOff.png"] forState:UIControlStateNormal];
    [radiobutton2 setBackgroundImage:[UIImage imageNamed:@"RBOn.png"] forState:UIControlStateSelected];
    [radiobutton2 addTarget:self action:@selector(radiobuttonSelected:) forControlEvents:UIControlEventTouchUpInside];

    
    [self.view addSubview:radiobutton1];
    [self.view addSubview:radiobutton2];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

-(void)checkboxSelected:(id)sender{

    
    if([checkbox isSelected]==YES)
    {
      [checkbox setSelected:NO];
    }
    else{
         [checkbox setSelected:YES];
    }
   
}
-(void)radiobuttonSelected:(id)sender{
    switch ([sender tag]) {
        case 0:
            if([radiobutton1 isSelected]==YES)
            {
                [radiobutton1 setSelected:NO];
                [radiobutton2 setSelected:YES];
            }
            else{
                [radiobutton1 setSelected:YES];
                [radiobutton2 setSelected:NO];
            }

            break;
        case 1:
            if([radiobutton2 isSelected]==YES)
            {
                [radiobutton2 setSelected:NO];
                [radiobutton1 setSelected:YES];
            }
            else{
                [radiobutton2 setSelected:YES];
                [radiobutton1 setSelected:NO];
            }

            break;
        default:
            break;
    }
   
}
@end

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Aditya 

      18 months ago

      Perfect solution

    • profile image

      Aravind 

      19 months ago

      thanks for the tutorial it helped for me

    • profile image

      Padma 

      19 months ago

      Very useful thanks a lot

    • profile image

      raja 

      19 months ago

      i want radio button in tableview cell

    • profile image

      sushant jagtap 

      20 months ago

      thank you for this awesome and simple solution...

    • profile image

      hitesh rakholiya 

      2 years ago

      awesome tutorial

    • profile image

      @dubai 

      2 years ago

      This is what is was looking for a long time. Glad i found this blog soon which solved my problem in minutes. Thank you so much for this.

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      3 years ago from Canada

      You could create with code or switch to HTML5/Javascript and use a the UIWebView or use the example above.

      Thanks for the feedback

    • profile image

      jaqen 

      3 years ago

      hi, thx for this tutorials. btw what if i had more than 5 radio, should i type all of that? thx

    • profile image

      Mittal 

      3 years ago

      Very Helpful

    • profile image

      pradeep 

      3 years ago

      this is very useful tutorials.

    • profile image

      pange 

      4 years ago

      I'm new to iPhone app development and I found that this tutorial is one of great resource that I got :D

      thank you!

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      4 years ago from Canada

      Thanks for the great feedback

    • profile image

      nathankalam 

      4 years ago

      This is very useful. it would appreciate for multiple check box. Thanks for everything

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      4 years ago from Canada

      Cool thanks

    • profile image

      Santosh 

      4 years ago

      Thanks a lot..crisp and clear

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      5 years ago from Canada

      Thank you Falgun Ruparella

    • profile image

      Falgun Ruparelia 

      5 years ago

      It really helped a lot.... Good explanatory article ...

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      5 years ago from Canada

      Thanks

    • profile image

      Guntarion 

      5 years ago

      This is very useful, kevin languedoc. Thank you verymuch! :-)

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      5 years ago from Canada

      Great I am glad I was able to help

    • profile image

      Vibhs 

      5 years ago

      That is what I've been looking for long time...

    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, owlcation.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://owlcation.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)