Simple iPhone Checkbox Button (with sample code)

By weheartgames / June 4th, 2009 / Resources / 53 Comments

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:
;

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!

Add Comment

53 Responses

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

  • a little bit shorter

    - (IBAction)checkboxButton:(id)sender{

    checkboxButton.selected = !checkboxButton.selected;

    }

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

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

  • 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

  • - (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.

  • 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 :-)

    • hi

      this is also pretty good…….

    • 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;
      }

    • 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;
      }

      • I get an error with:
        [scrollView addSubview: chkbox];

        and this code:
        [chkbox release];

        Says “Unknown receiver ‘scrollView’ did you mean ‘UIScrollView’.
        ARC forbids explict message send for release

  • Thank you!

  • 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.

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

  • Thanks for help – just what I needed :)

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

    By Patricia Hendricks / 20th November 2009 at 10:38 am Reply
  • 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.

  • Pingback: Checkbox in de iPhone

  • Awesome idea. Thanks so much

  • Awesome idea. Thanks so much

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

  • 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

  • very good tutorial . definately it will help us

    Thanks

  • Beautiful…easy :-)
    Thanks!

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

  • yeah its prety good

  • 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……

    By Dhanunjaya Mangali / 20th July 2010 at 4:29 am Reply
  • Can I use your checkbox pictures in my app?

  • 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];
    }
    }

    }

  • 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

    • 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.

      • 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,

  • 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?

  • Thanks…. it works…… :)

  • Thank you for posting this. 

    Just what I needed. 

    And thanks to those who suggested improvements as well.

    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.

  • 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.

  • where to set the image if the button clicked

  • 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?

  • Thanks, this helped me.

    By shashidhar yamsani / 11th November 2011 at 1:54 am Reply
  • 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

    • 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! :)

  • 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 

  •  Awesome……

  • Question:

    How would I use this button throughout my iOS application without re-creating it where ever I need it? I’m a noob so apologies in advance.

    So, for instance, I’d like to put this button in a xib then load it’s xib in other xibs (or in the main story board) and have the button appear as it does when initially created–with the images for each state, etc.

    Any one know?

  • I change IBAction checkboxButton for multi-checkbox

    - (IBAction)checkboxButton:(id)sender{
    UIButton * checkbox = (UIButton *)sender;
    if(checkbox.tag == 0){
    [checkbox setSelected:YES];
    checkbox.tag = 1;
    }
    else {
    [checkbox setSelected:NO];
    checkbox.tag = 0;
    }



Add a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Go on top