Home
  • home

  • face race

  • blog

  • client work

  • contact

« PAX 10, here we come!

PAX 10 contest winners »
Simple iPhone Checkbox Button (with sample code)
Mike Berg
04
Jun 2009

I was looking around for an easy way to create a checkbox on the iPhone, and it turns out there isn’t one. At least, not one readily available. I found a couple of posts, and thought that there should be an easy way to do this.

In that first post, he refers to this:
[button setSelected:YES];

So the method I came up with was to have a button with separate graphics for the required three states:

checkbox Normal

checkbox-pressed Highlighted

checkbox-checked Selected

Each of these corresponds with the button states that can be set in Interface Builder. Be sure to set the images in the “Image” pop-up, NOT the “Background” pop-up. If you put it in the Background, it will scale the image to fill the size of the button. Putting it in the “Image” pop-up centers the image in the button and allows us to make the clickable area of the button larger than the checkbox itself, which is important for such a small button.

checkbox-ib

The code itself looks like this:

- (IBAction)checkboxButton:(id)sender{
if (checkboxSelected == 0){
[checkboxButton setSelected:YES];
checkboxSelected = 1;
} else {
[checkboxButton setSelected:NO];
checkboxSelected = 0;
}
}

Download the source code (full Xcode project) here. You can see that there is an IBAction and IBOutlet as well. Make sure you make those connections in Interface Builder, or the button won’t work.

I’m pretty new at programming so if I’m doing something wrong here, please let me know!

Category: Blog, Resources
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
  • cico

    brilliant, thank you, those images are exactly what I was looking for when I stumbled on both the posts you linked.

  • Eugene

    a little bit shorter

    - (IBAction)checkboxButton:(id)sender{

    checkboxButton.selected = !checkboxButton.selected;

    }

  • Charles

    Nice!! Keep posting more examples like this…

    I went through your code, but I am unsure how you change the state of the button when clicked. can you give me a clue?

    Thx

  • admin

    - (IBAction)checkboxButton: is what gets called when the button is clicked. [checkboxButton setSelected:YES]; is what sets the “selected” state of the button. Eugene provides a more straightforward method of selecting and deselecting a button, but that (as far as I can tell) doesn’t allow you to call a separate function based on whether or not the button is selected.

  • Agha

    There is good a news and there is a bad news.
    Well. Your code works. :-)
    Bad News: It does not work if you want to control the state your self or like me I do not have nib file. :-(
    setImage function only works where you are not controlling the state of the button. Out of option. We can’t use it.
    Next question: Do you want 2 stage/ 3 stage or even 4 stage button. Your code works with 3 stages.
    But I need 2 stages so (I do not have nib file so I have to add at loadview) and create
    @property (assign) BOOL isOn; in your SomenameViewController class

    - (void)loadView
    {
    UIButton* Chkbutton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f,40.0f, 40.0f)];
    [Chkbutton setBackgroundImage:[UIImage imageNamed:@"SomeImageOff.png"] forState:UIControlStateNormal];
    [Chkbutton setCenter:CGPointMake(someValue)];
    [contentView addSubview: rhsbutton];
    [rhsbutton addTarget:self action:@selector(toggleButton:) forControlEvents: UIControlEventTouchUpInside];
    [Chkbutton release];
    }

    - (void) toggleButton: (id) sender
    {
    isOn = !isOn;
    UIButton* Chkbutton = (UIButton*) sender;
    if (isOn == NO)
    [Chkbutton setBackgroundImage:[UIImage imageNamed:@"SomeImageOff.png"] forState:UIControlStateNormal];
    else
    [Chkbutton setBackgroundImage:[UIImage imageNamed:@"SomeImageOn.png"] forState:UIControlStateNormal];
    }

    for 3 or 4 stage button please check The iPhone Developer’s Cookbook Toggle Button Example.

    -Agha :-)

  • Name

    Thank you!

  • Ron

    I would ask why you aren't using the built-in UISwitch control, which is a common control which provides the same capability. While the checkbox is a commonly understood control to many, I think it will look and feel out of place on the device — the switch the right thing to use I would venture to say.

  • http://weheartgames.com WeHeartGames

    Yes, UISwitch is definitely the preferred choice for sticking with Apple's UI, etc. But sometimes… SOMETIMES, it's just a bit too big. 320×480 starts to feel pretty small at times!

  • Marc

    Thanks for help – just what I needed :)

  • Patricia Hendricks

    Hey are we allowed to use these checkbox images? If not how can we get permission?

  • http://weheartgames.com WeHeartGames

    Yes, feel free to use the images.

  • Patricia Hendricks

    Thanks a lot!

  • koti1

    hi,
    i have one view, in that i put i take one round rect button .And i have check box images in resources folder.i given connections correcltly,but it would not work .click method is not working.

  • http://weheartgames.com WeHeartGames

    Without more detail I wouldn't be able to know what's going on. If you want to email me your project, I could have a look at it: mike [at] weheartgames dot com

  • Pingback: Checkbox in de iPhone

  • Newb

    Awesome idea. Thanks so much

  • Newb

    Awesome idea. Thanks so much

  • http://developers-life.com/ SAKrisT

    - (IBAction)checkboxButton:(UIButton *)button{
    button.selected = !button.selected;
    }

  • Mirrorps

    Nice Post!
    Just to clarify – the checkboxSelected variable should be set to be equal (=) to 0 in the viewDidLoad Controller and not compared to 0 (==) ? :

    - (void)viewDidLoad {
    checkboxSelected == 0; // <–this one to become => checkboxSelected = 0;
    [super viewDidLoad];
    }

    Regards,
    Mirrorps

  • krishnagupta

    very good tutorial . definately it will help us

    Thanks

  • art

    Beautiful…easy :-)
    Thanks!

  • http://donggi.net Donggi

    Thank you for the good tutorial.
    I was looking for the button images. Great!

  • http://www.andrewtheis.net/ Andrew Theis

    If you get errors using this [sender setSelected:![sender isSelected]]; works too.

  • Balu Guru

    yeah its prety good

  • http://profiles.yahoo.com/u/RTEKNQZLQUU3624ERLXHXC7XNQ Lucas Still

    I just stumbled upon this page in search of a good checkbox and this was exactly what I was looking for. I decided to implement this without IB and Andrew's tip is definitely what you need to use. Thanks Mike for the great tutorial and thanks Andrew for the tip!

  • Mdhanu143

    hi

    this is also pretty good…….

  • Dhanunjaya Mangali

    hi friend,

    checkbox example is more helpful for me.

    I am also new to iphone development and can u please tell me hoe to play the streaming video from url
    if you know this how to do please let me know
    thanks in advance……

  • Werdanne

    Can I use your checkbox pictures in my app?

  • http://weheartgames.com Anonymous

    Yes, you can use them.

  • Jim_geldermann

    Thanks for starting this thread – to simplify Agha’s post with your project I have modified your checked code to

    -(IBAction)setChecked:(id)sender{
    if([sender isKindOfClass:[UIButton class]]){
    UIButton *tmpButton = sender;

    if(!tmpButton.selected){
    [sender setSelected:YES];
    }
    else{
    [sender setSelected:NO];
    }
    }

    }

  • http://www.appatapp.co.uk Tom_tatrials

    how can you implement more than one? I copied the code and called it button 2 and when the second button is pressed, the first gets highlighted, it is not connected to the first button either.

    Help,

    Email, tom_tatrials@hotmail.co.uk

    Thanks

  • http://weheartgames.com Anonymous

    If using more than one, change all the names and variables so that they’re unique:
    checkboxButton would be checkbox1Button, checkbox2Button, etc.
    checkboxSelected would be checkbox1Selected, checkbox2Selected, etc.

  • http://www.facebook.com/profile.php?id=1264370071 Rachel Baker

    I cannot get it to work. When you click on the button, it doesn’t change… I went thru all of your code and placed it in the appropriate places and the links are there for the outlets. It acts as if it doesn’t know to change the image to the other image. Does it do it in the XIB or the code?

  • James

    works for me…

  • http://weheartgames.com Anonymous

    Is it the downloaded sample project that isn’t working for you? Or your own project. Are both the Outlets *and* Actions linked correctly?

  • Mkt

    Thanks…. it works…… :)

  • Dave

    Thank you for posting this. 

    Just what I needed. 

    And thanks to those who suggested improvements as well.

    Dave.

  • Dave

    I do have one question….

    There are TWO pressed states, one when enabling and one when disabling.

    When enabling it shows checkbox-pressed – all ok so far.

    When de-selecting – it inverts the CONTENTS of the checkbox. Th corners seem to stay white.

    This has me baffled. I have been trying to build a radio button based on this idea 
    and the entire square is grayed when you press to deselect.

    I know it must be something pretty simple that I am missing like transparency (or choice of shape or something) but could you put me out of my misery and let me know?

    Thanks,
    Dave.

  • Dave

    I do have one question….

    There are TWO pressed states, one when enabling and one when disabling.

    When enabling it shows checkbox-pressed – all ok so far.

    When de-selecting – it inverts the CONTENTS of the checkbox. Th corners seem to stay white.

    This has me baffled. I have been trying to build a radio button based on this idea 
    and the entire square is grayed when you press to deselect.

    I know it must be something pretty simple that I am missing like transparency (or choice of shape or something) but could you put me out of my misery and let me know?

    Thanks,
    Dave.

  • Gbm Gee

    where to set the image if the button clicked

  • solara

    This is how I done it, works for me:

    - (void)viewDidLoad {
     
        // create a checkbox
        UIButton* chkbox = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f,40.0f, 40.0f)];
        [chkbox setBackgroundImage:[UIImage imageNamed:@"checkbox.png"] forState:UIControlStateNormal];
        [chkbox setBackgroundImage:[UIImage imageNamed:@"checkbox-pressed.png"] forState:UIControlStateHighlighted];
        [chkbox setBackgroundImage:[UIImage imageNamed:@"checkbox-checked.png"] forState:UIControlStateSelected];
        [chkbox setCenter:CGPointMake(100,200)];
        [scrollView addSubview: chkbox];
        [chkbox addTarget:self action:@selector(ToggleCheckBox:) forControlEvents: UIControlEventTouchUpInside];
        [chkbox release];
        [super viewDidLoad];
    }

    - (IBAction)ToggleCheckBox:(UIButton *)button{
        button.selected = !button.selected;
    }

  • solara

    This is how I done it, works for me:

    - (void)viewDidLoad {
     
        // create a checkbox
        UIButton* chkbox = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f,40.0f, 40.0f)];
        [chkbox setBackgroundImage:[UIImage imageNamed:@"checkbox.png"] forState:UIControlStateNormal];
        [chkbox setBackgroundImage:[UIImage imageNamed:@"checkbox-pressed.png"] forState:UIControlStateHighlighted];
        [chkbox setBackgroundImage:[UIImage imageNamed:@"checkbox-checked.png"] forState:UIControlStateSelected];
        [chkbox setCenter:CGPointMake(100,200)];
        [scrollView addSubview: chkbox];
        [chkbox addTarget:self action:@selector(ToggleCheckBox:) forControlEvents: UIControlEventTouchUpInside];
        [chkbox release];
        [super viewDidLoad];
    }

    - (IBAction)ToggleCheckBox:(UIButton *)button{
        button.selected = !button.selected;
    }

  • Helps please

    I am getting very frustrated with this. I have got more than one tick box, when loaded up in simulator, i have a line of buttons. The FIRST one I click is a ‘one tap’ button while all the others after the first one are ‘double tap’ buttons.

    No matter which one you click first when the app is loaded its always one tap then the others are double. Can anyone help me out?

  • helps please

    That doesn’t work, the code errors out. I can change the checkbox names but checkbox selected cannot be changed. 

    Can you add another button to your code so we know exactly how to do it please?

    Thanks,

  • shashidhar yamsani

    Thanks, this helped me.

  • Betti

    Hello, your code works fine. But when I close und restart the application my selections are gone … Do you have an idea to save the boxes are selected ba starting the app next time. Sorry for ma bad english

  • http://weheartgames.com Anonymous

    Yes, this method is simply setting a local variable, which would definitely be reset when you quit the app. Saving the state of your application when you quit is a whole other ballgame. I’m sure there are other articles online, written by people more qualified than me to talk about it. Have a look around, I’m sure you’ll find something! :)

  • WhitePaper

    Good Job .. but take care when you wanna assign value to boolean 
    we usually use  checkBoxSelected=0  not   checkBoxSelected==0  we use == in case of conditional statements life  IF , WHILE,…etc 

« PAX 10, here we come!

PAX 10 contest winners »

    Follow on:

    RSS | Twitter | YouTube

latest blog posts

  • Setting the default file format for new slices in Photoshop
  • How to export Flash SWF animations to PNG sequences
  • Photoshop for devs: Required reading
  • New t-shirt: Boost Greed
  • Rush City icon time lapse

Buy it now
on the App Store

A camera-based
party game for iPhone

© 2012 - We Heart Games Inc. All rights reserved.