iPhone SDK – How To Add CheckBox Control
Posted in iphone on December 15th, 2009 by Abhishek Balaria – 1 CommentThis is quite a common requirement to be able to add a custom checkbox control in an iPhone app. In the Interface builder -> Tools ->library there is no CheckBox control while other controls like Label and Text Field are there. Here is how I implemented it. I would be interested in hearing about how others went about doing it.
You can use the UIButton control to make a CheckBox.
In your project, in the resources folder add the images e.g. the ones attached with in this post “checkbox-selected.png” and “checkbox.png”.
Define the members as follows in “CheckBoxViewController.h”
@interface CheckBoxViewController : UIViewController{BOOL checkboxSelected;UIButton *checkBox;UILabel *checkBoxLabel;}
Uncomment the viewDidLoad in “CheckBoxViewController.m” and use the following code.
- (void)viewDidLoad { [super viewDidLoad]; checkBox = [[UIButton alloc] initWithFrame:CGRectMake(60, 100, 16, 16)]; checkBox.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; checkBox.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter; // Image for normal state UIImage *newNormalImage = [UIImage imageNamed:@"checkbox.png"]; [checkBox setBackgroundImage:newNormalImage forState:UIControlStateNormal]; // Image for highlighted state UIImage *newHighlightedImage = [UIImage imageNamed:@"checkbox-selected.png"]; [checkBox setBackgroundImage:newHighlightedImage forState:UIControlStateHighlighted]; // Image for selected state UIImage *newSelectedImage = [UIImage imageNamed:@"checkbox-selected.png"]; [checkBox setBackgroundImage:newSelectedImage forState:UIControlStateSelected]; [checkBox addTarget:self action:@selector(checkBoxSelect:)forControlEvents:UIControlEventTouchUpInside]; checkBox.adjustsImageWhenHighlighted = YES; [checkBox setBackgroundColor:[UIColor clearColor]]; [[self view] addSubview:checkBox]; checkBoxLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 90, 200, 40)]; [checkBoxLabel setText:@"Check Box"]; [checkBox setBackgroundColor:[[ self view] backgroundColor]]; [[self view] addSubview:checkBoxLabel]; }
And add the following action method
-(void)checkBoxSelect:(id)sender { if (checkboxSelected == 0) { [checkBox setSelected:YES]; [checkBoxLabel setText:@"Check Box - Selected"]; checkboxSelected = 1; } else { [checkBox setSelected:NO]; [checkBoxLabel setText:@"Check Box"]; checkboxSelected = 0; } }
Build and Run the application, this will work as checkbox control.