AcademiaAgriculture & FarmingHumanitiesSocial SciencesSTEM

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

    • Vibhs 4 years ago

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

    • klanguedoc profile image
      Author

      Kevin Languedoc 4 years ago from Canada

      Great I am glad I was able to help

    • Guntarion 4 years ago

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

    • klanguedoc profile image
      Author

      Kevin Languedoc 4 years ago from Canada

      Thanks

    • Falgun Ruparelia 3 years ago

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

    • klanguedoc profile image
      Author

      Kevin Languedoc 3 years ago from Canada

      Thank you Falgun Ruparella

    • Santosh 3 years ago

      Thanks a lot..crisp and clear

    • klanguedoc profile image
      Author

      Kevin Languedoc 3 years ago from Canada

      Cool thanks

    • nathankalam 3 years ago

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

    • klanguedoc profile image
      Author

      Kevin Languedoc 3 years ago from Canada

      Thanks for the great feedback

    • pange 2 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!

    • pradeep 22 months ago

      this is very useful tutorials.

    • Mittal 20 months ago

      Very Helpful

    • jaqen 20 months ago

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

    • klanguedoc profile image
      Author

      Kevin Languedoc 20 months 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

    • @dubai 14 months 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.

    • hitesh rakholiya 5 months ago

      awesome tutorial

    • sushant jagtap 4 weeks ago

      thank you for this awesome and simple solution...

    • raja 2 weeks ago

      i want radio button in tableview cell

    • Padma 2 weeks ago

      Very useful thanks a lot

    • Aravind 7 days ago

      thanks for the tutorial it helped for me

    Click to Rate This Article