如何实现checkbox

iOS SDK 里并没有checkbox。下面教你如何用简单的code来实现。

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.

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.

一些stackoverflow上的其他方法:

http://stackoverflow.com/questions/8165895/stay-signed-in-option-for-iphone-app

http://stackoverflow.com/questions/650131/checkbox-in-iphone-application

http://stackoverflow.com/questions/5368196/how-create-simple-checkbox

你可能感兴趣的:(ios,checkbox)