Checkbox in iOS app

I need to add checkbox elements to my form. I know that there is no such control in the iOS SDK. How can i do this?

+34
checkbox ios iphone
Mar 16 '09 at 12:05
source share
13 answers

it also confused me, and I found another solution that works well for me and avoids the use of images.

  • Add a new label object in Interface Builder.
  • Create an IBOutlet property in Xcode and connect it to it. In the code below, I called it "fullPaid" because I want to know if someone paid the full amount.
  • Add 2 features below. The touchhesBegan function checks if you touched the fullPaid label somewhere inside the object, and if so, it calls the togglePaidStatus function. The togglePaidStatus function sets two lines that have Unicode characters representing an empty field (\ u2610) and a marked field (\ u2611), respectively. Then it compares what is currently in the "fullPaid" object and switches it to a different line.

You can call the togglePaidStatus function in the viewDidLoad function to initially set it to an empty string.

Obviously, you can add additional checks to prevent users from checking this box if the label is not enabled but not shown below.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; if (CGRectContainsPoint([fullyPaid frame], [touch locationInView:self.view])) { [self togglePaidStatus]; } } -(void) togglePaidStatus { NSString *untickedBoxStr = [[NSString alloc] initWithString:@"\u2610"]; NSString *tickedBoxStr = [[NSString alloc] initWithString:@"\u2611"]; if ([fullyPaid.text isEqualToString:tickedBoxStr]) { fullyPaid.text = untickedBoxStr; } else { fullyPaid.text = tickedBoxStr; } [tickedBoxStr release]; [untickedBoxStr release]; } 
+31
Apr 10 '10 at 21:23
source share

Generally, you should use UISwitch for check-like functionality.

You can roll yourself using the image control with two images (marked / unchecked) and switching images when they touch the /

+25
Mar 16 '09 at 12:12
source share

If you show a group of parameters, and the user can select one of them, use the table with an additional flag and a different text color in the selected row.

If you have one option, it is best to use a switch. If you cannot or do not want to, use the button, setting the normal image in an empty field and the selected image in the marked field. You will need to make these two images yourself or find a spare graphic to use for them.

+11
Mar 16 '09 at 12:33
source share

Expanding to the Adrean idea , I achieved this using a very simple approach.
My idea is to change the button (say checkBtn ) depending on its state, and then change the state of the button in IBAction .
Below is the code as I did it:

 - (void)viewDidLoad { [super viewDidLoad]; [checkBtn setTitle:@"\u2610" forState:UIControlStateNormal]; // uncheck the button in normal state [checkBtn setTitle:@"\u2611" forState:UIControlStateSelected]; // check the button in selected state } - (IBAction)checkButtonTapped:(UIButton*)sender { sender.selected = !sender.selected; // toggle button selected state if (sender.state == UIControlStateSelected) { // do something when button is checked } else { // do something when button is unchecked } } 
+8
Mar 19 '14 at 4:17
source share

I wanted to do this programmatically, and also solve a problem that was too small. This is adapted from various sources, including Mike and Mike, the commentator on Aga.

In the title

 @interface YourViewController : UIViewController { BOOL checkboxSelected; UIButton *checkboxButton; } @property BOOL checkboxSelected;; @property (nonatomic, retain) UIButton *checkboxButton; -(void)toggleButton:(id)sender; 

And in your implementation

 // put this in your viewDidLoad method. if you put it somewhere else, you'll probably have to change the self.view to something else // create the checkbox. the width and height are larger than actual image, because we are creating the hit area which also covers the label UIButton* checkBox = [[UIButton alloc] initWithFrame:CGRectMake(100, 60,120, 44)]; [checkBox setImage:[UIImage imageNamed:@"checkbox.png"] forState:UIControlStateNormal]; // uncomment below to see the hit area // [checkBox setBackgroundColor:[UIColor redColor]]; [checkBox addTarget:self action:@selector(toggleButton:) forControlEvents: UIControlEventTouchUpInside]; // make the button image flush left, and then push the image 20px left [checkBox setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft]; [checkBox setImageEdgeInsets:UIEdgeInsetsMake(0.0, 20.0, 0.0, 0.0)]; [self.view addSubview:checkBox]; // add checkbox text text UILabel *checkBoxLabel = [[UILabel alloc] initWithFrame:CGRectMake(140, 74,200, 16)]; [checkBoxLabel setFont:[UIFont boldSystemFontOfSize:14]]; [checkBoxLabel setTextColor:[UIColor whiteColor]]; [checkBoxLabel setBackgroundColor:[UIColor clearColor]]; [checkBoxLabel setText:@"Checkbox"]; [self.view addSubview:checkBox]; // release the buttons [checkBox release]; [checkBoxLabel release]; 

And add this method too:

 - (void)toggleButton: (id) sender { checkboxSelected = !checkboxSelected; UIButton* check = (UIButton*) sender; if (checkboxSelected == NO) [check setImage:[UIImage imageNamed:@"checkbox.png"] forState:UIControlStateNormal]; else [check setImage:[UIImage imageNamed:@"checkbox-checked.png"] forState:UIControlStateNormal]; } 
+6
May 21 '10 at 16:46
source share

Here is my checkbox version for iphone.

This is one class that extends UIButton. It is simple, so I will embed it here.

CheckBoxButton.h file contents

 #import <UIKit/UIKit.h> @interface CheckBoxButton : UIButton @property(nonatomic,assign)IBInspectable BOOL isChecked; @end 

CheckBoxButton.m file contents

 #import "CheckBoxButton.h" @interface CheckBoxButton() @property(nonatomic,strong)IBInspectable UIImage* checkedStateImage; @property(nonatomic,strong)IBInspectable UIImage* uncheckedStateImage; @end @implementation CheckBoxButton -(id)init { self = [super init]; if(self) { [self addTarget:self action:@selector(switchState) forControlEvents:UIControlEventTouchUpInside]; } return self; } -(id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if(self) { [self addTarget:self action:@selector(switchState) forControlEvents:UIControlEventTouchUpInside]; } return self; } -(id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if(self) { [self addTarget:self action:@selector(switchState) forControlEvents:UIControlEventTouchUpInside]; } return self; } -(void)setIsChecked:(BOOL)isChecked { _isChecked = isChecked; if(isChecked) { [self setImage:self.checkedStateImage forState:UIControlStateNormal]; } else { [self setImage:self.uncheckedStateImage forState:UIControlStateNormal]; } } -(void)switchState { self.isChecked = !self.isChecked; [self sendActionsForControlEvents:UIControlEventValueChanged]; } @end 

You can set images for checked / unchecked, as well as isChecked properties in the visual studio attribute inspector.

enter image description here

To add a CheckBoxButton to a storyboard or xib, simply add a UIButton and set your own class, as in the following image.

enter image description here

Button

will send a UIControlEventValueChanged event, each time the isChecked state changes.

+6
Dec 31 '15 at 13:44
source share

Everyones code here is very long, a bit dirty, and could be made much simpler. I have a GitHub project for a subclass of UIControl that you can download and test, and gives you almost your own user interface element:

https://github.com/Brayden/UICheckbox

+4
Jul 18 2018-12-18T00:
source share

I like Adrian's idea of ​​using symbols, not images. But I do not like the box, it only needs a checkmark (@ "\ u2713"). I draw a box (rounded box) programmatically and place a UILabel containing a checkmark inside it. This implementation method makes it easy to use a custom view in any application without worrying about any dependent resource. You can also easily adjust the color of the checkmark, rounded border and background. Here is the full code:

 #import <UIKit/UIKit.h> @class CheckBoxView; @protocol CheckBoxViewDelegate - (void) checkBoxValueChanged:(CheckBoxView *) cview; @end @interface CheckBoxView : UIView { UILabel *checkMark; bool isOn; UIColor *color; NSObject<CheckBoxViewDelegate> *delegate; } @property(readonly) bool isOn; @property(assign) NSObject<CheckBoxViewDelegate> *delegate; - (void) drawRoundedRect:(CGRect) rect inContext:(CGContextRef) context; @end #import "CheckBoxView.h" #define SIZE 30.0 #define STROKE_WIDTH 2.0 #define ALPHA .6 #define RADIUS 5.0 @implementation CheckBoxView @synthesize isOn, delegate; - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, SIZE, SIZE)])) { // Initialization code } //UIColor *color = [UIColor blackColor]; color = [[UIColor alloc] initWithWhite:.0 alpha:ALPHA]; self.backgroundColor = [UIColor clearColor]; checkMark = [[UILabel alloc] initWithFrame:CGRectMake(STROKE_WIDTH, STROKE_WIDTH, SIZE - 2 * STROKE_WIDTH, SIZE - 2*STROKE_WIDTH)]; checkMark.font = [UIFont systemFontOfSize:25.]; checkMark.text = @"\u2713"; checkMark.backgroundColor = [UIColor clearColor]; checkMark.textAlignment = UITextAlignmentCenter; //checkMark.textColor = [UIColor redColor]; [self addSubview:checkMark]; [checkMark setHidden:TRUE]; isOn = FALSE; return self; } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code CGRect _rect = CGRectMake(STROKE_WIDTH, STROKE_WIDTH, SIZE - 2 * STROKE_WIDTH, SIZE - 2*STROKE_WIDTH); [self drawRoundedRect:_rect inContext:UIGraphicsGetCurrentContext()]; [checkMark setHidden:!isOn]; } - (void)dealloc { [checkMark release]; [color release]; [super dealloc]; } - (void) drawRoundedRect:(CGRect) rect inContext:(CGContextRef) context{ CGContextBeginPath(context); CGContextSetLineWidth(context, STROKE_WIDTH); CGContextSetStrokeColorWithColor(context, [color CGColor]); CGContextMoveToPoint(context, CGRectGetMinX(rect) + RADIUS, CGRectGetMinY(rect)); CGContextAddArc(context, CGRectGetMaxX(rect) - RADIUS, CGRectGetMinY(rect) + RADIUS, RADIUS, 3 * M_PI / 2, 0, 0); CGContextAddArc(context, CGRectGetMaxX(rect) - RADIUS, CGRectGetMaxY(rect) - RADIUS, RADIUS, 0, M_PI / 2, 0); CGContextAddArc(context, CGRectGetMinX(rect) + RADIUS, CGRectGetMaxY(rect) - RADIUS, RADIUS, M_PI / 2, M_PI, 0); CGContextAddArc(context, CGRectGetMinX(rect) + RADIUS, CGRectGetMinY(rect) + RADIUS, RADIUS, M_PI, 3 * M_PI / 2, 0); CGContextClosePath(context); CGContextStrokePath(context); } #pragma mark Touch - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [touches anyObject]; CGPoint loc = [touch locationInView:self]; if(CGRectContainsPoint(self.bounds, loc)){ isOn = !isOn; //[self setNeedsDisplay]; [checkMark setHidden:!isOn]; if([delegate respondsToSelector:@selector(checkBoxValueChanged:)]){ [delegate checkBoxValueChanged:self]; } } } 
+1
Jul 23 '10 at 9:41
source share

in .h file

 #import <UIKit/UIKit.h> @interface ViewController : UIViewController { BOOL isChecked; UIImageView * checkBoxIV; } @end 

And the .m file

 - (void)viewDidLoad { [super viewDidLoad]; isChecked = NO; //change this property according to your need checkBoxIV = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 15, 15)]; checkBoxIV.image =[UIImage imageNamed:@"checkbox_unchecked.png"]; checkBoxIV.userInteractionEnabled = YES; UITapGestureRecognizer *checkBoxIVTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlecheckBoxIVTapGestureTap:)]; checkBoxIVTapGesture.numberOfTapsRequired = 1; [checkBoxIV addGestureRecognizer:checkBoxIVTapGesture]; } - (void)handlecheckBoxIVTapGestureTap:(UITapGestureRecognizer *)recognizer { if (isChecked) { isChecked = NO; checkBoxIV.image =[UIImage imageNamed:@"checkbox_unchecked.png"]; }else{ isChecked = YES; checkBoxIV.image =[UIImage imageNamed:@"checkbox_checked.png"]; } } 

This will do the trick ...

+1
Jun 14 '13 at 10:12
source share

I did this with a UITextField so as not to draw anything strange, but I liked to insert text as Unicode text (Unicode character CHECK MARK (U + 2713)) for NSString: @ "\ u2713".

So in my .h file (implementation of the UITextField protocol 'UITextFieldDelegate'):

 UITextField * myCheckBox; 

In my view, DidLoad or functions to prepare the user interface:

 ... myCheckBox = [[UITextField alloc] initWithFrame:aFrame]; myCheckBox.borderStyle = UITextBorderStyleRoundedRect; // System look like myCheckBox.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; myCheckBox.textAlignment = NSTextAlignmentLeft; myCheckBox.delegate = self; myCheckBox.text = @" -"; // Initial text of the checkbox... editable! ... 

Then add an event selector for reating in the touch event and raise the responseSelected event:

 ... UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(checkboxSelected)]; [myCheckBox addGestureRecognizer:tapGesture]; ... 

Finally, answer this selector

 -(void) checkboxSelected { if ([self isChecked]) { // Uncheck the selection myCheckBox.text = @" -"; }else{ //Check the selection myCheckBox.text = @"\u2713"; } } 

The 'isChecked' function only checks if the text is a @ "\ u2713" mark. To prevent the keyboard from showing when selecting a text field, use the UITextField event 'textFieldShouldBeginEditing' and add an event selector to control the selection:

 -(BOOL)textFieldShouldBeginEditing:(UITextField *)textField { // Question selected form the checkbox [self checkboxSelected]; // Hide both keyboard and blinking cursor. return NO; } 
+1
Oct 07 '14 at 11:13
source share

Subclass of UIButton, release the button to view the controller, select it and change the class name to CheckBox in the identity inspector.

 #import "CheckBox.h" @implementation CheckBox #define checked_icon @"checked_box_icon.png" #define empty_icon @"empty_box_icon.png" - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { [self setImage:[UIImage imageNamed:empty_icon] forState:UIControlStateNormal]; [self addTarget:self action:@selector(didTouchButton) forControlEvents:UIControlEventTouchUpInside]; } return self; } - (void)didTouchButton { selected = !selected; if (selected) [self setImage:[UIImage imageNamed:checked_icon] forState:UIControlStateNormal]; else [self setImage:[UIImage imageNamed:empty_icon] forState:UIControlStateNormal]; } @end 
+1
May 13 '15 at 11:59
source share

user Aruna Lakmal; FYI, when you add this code to IB, as you describe that initWithFrame is not called, initWithCoder. Deploy initWithCoder and it will work as your description.

0
Jan 20 '13 at 3:15
source share

I made one recently. Free purchase from GitHub. Let's see if that helps. Effect like

enter image description here

0
Apr 01 '19 at 20:36
source share



All Articles