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!