Checkbox in iOS application

前端 未结 13 1374
野趣味
野趣味 2020-12-01 01:48

I need to add checkbox controls to my form. I know that there is no such control in iOS SDK. How could I do this?

相关标签:
13条回答
  • 2020-12-01 02:27

    Here is my version of checkbox for iphone.

    It is single class which extends UIButton. It is simple so i will paste it here.

    CheckBoxButton.h file content

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

    CheckBoxButton.m file content

    #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 property in the attribute inspector of visual studio.

    enter image description here

    To add CheckBoxButton in storyboard or xib, simple add UIButton and set custom class like on next image.

    enter image description here

    Button will send UIControlEventValueChanged event, every time when isChecked state is changed.

    0 讨论(0)
  • 2020-12-01 02:29

    If you're showing a group of options and the user can select one of them, use a tableview with a checkmark accessory and a different text color on the selected row.

    If you have a single option, your best bet is to use a switch. If you can't or don't want to, use a button, setting the normal image to an empty box and the selected image to a checked box. You'll have to make those two images yourself or find stock graphics to use for them.

    0 讨论(0)
  • 2020-12-01 02:30

    in .h file

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

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

    0 讨论(0)
  • 2020-12-01 02:32

    Everyones code here is very long, slightly messy, and could be done a lot simpler. I have a project on GitHub that subclass UIControl that you can download and check out and gives you an almost native checkbox UI element:

    https://github.com/Brayden/UICheckbox

    0 讨论(0)
  • 2020-12-01 02:33

    I like the idea of Adrian to use the characters rather than images. But I don't like the box, it need only the checkmark itself (@"\u2713"). I draw a box (a rounded box) programmatically and place an UILabel contains the checkmark inside it. This way of implementation makes it easy to use the custom view in any application without care about any dependent resource. You can also customize the color of the checkmark, the rounded box and the background with ease. Here's the complete 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];
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-01 02:34

    I wanted to do this programmatically, and also solve the problem that the hit area was really too small. This is adapted from various sources, including Mike and Mike's commenter Agha.

    In your header

    @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's 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 put this method in 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];
    
    }
    
    0 讨论(0)
提交回复
热议问题