iOS应用程序中的checkbox

我需要添加checkbox控件到我的表单。 我知道在iOS SDK中没有这样的控制。 我怎么能这样做?

这也一直让我生气,我发现了一个不同的解决scheme,适合我,避免使用图像。

  1. 添加一个新的标签对象到Interface Builder。
  2. 在Xcode中创build一个IBOutlet属性并将其连接到它。 在下面的代码中,我把它叫做'fullypaid',因为我想知道是否有人已经完全支付了一笔钱。
  3. 添加下面的2个函数。 'touchesBegan'函数检查是否触摸'fullyPaid'标签对象内的某个地方,如果是,则调用“togglePaidStatus”函数。 “togglePaidStatus”函数分别设置两个string,其中unicode字符分别表示一个空框(\ u2610)和一个checkbox(\ u2611)。 然后比较'fullyPaid'对象中的当前内容,并将其与另一个string进行切换。

您可能需要在viewDidLoad函数中调用togglePaidStatus函数将其初始化为空string。

显然你可以添加额外的检查,以防止用户切换checkbox,如果标签没有启用,但没有显示在下面。

-(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]; } 

通常,您可以使用UISwitch来实现类似checkbox的function。

你可以通过使用带有两个图像的图像控件(选中/未选中)来滚动你的图像,并在图像触摸控制/

如果您正在显示一组选项,并且用户可以select其中一个选项,请在所选行上使用带有复选标记附件和不同文本颜色的tableview。

如果你有一个选项,你最好的select是使用开关。 如果您不能或不想使用button,请将正常图像设置为空白框,并将所选图像设置为checkbox。 你将不得不自己做这两个图像或find股票graphics来使用它们。

扩展到Adrean的想法 ,我用一个非常简单的方法实现了这一点。
我的想法是改变button(让我们说checkBtn )文本取决于其状态,然后更改其IBActionbutton的状态。
以下是我如何做到这一点的代码:

 - (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's selected state if (sender.state == UIControlStateSelected) { // do something when button is checked } else { // do something when button is unchecked } } 

我想以编程的方式做到这一点,也解决了这个热门地区太小的问题。 这是从各种来源,包括迈克和迈克的评论者Agha。

在你的头上

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

并在您的实施

 // 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]; 

并把这个方法也放在:

 - (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]; } 

这是我的iPhonecheckbox的版本。

它是扩展UIButton的单类。 这很简单,所以我会把它粘贴在这里。

CheckBoxButton.h文件内容

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

CheckBoxButton.m文件内容

 #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 

您可以在Visual Studio的属性检查器中为checked / unchecked以及isChecked属性设置图像。

在这里输入图像说明

要添加故事板或xib中的CheckBoxButton,只需简单地添加UIButton并设置自定义类,如下图所示。

在这里输入图像说明

每发生一次isChecked状态改变,button将发送UIControlEventValueChanged事件。

这里所有的代码都非常长,稍微杂乱,可以做得更简单。 我在GitHub上有一个子类UIControl的项目,你可以下载和检查,并给你一个几乎原生的checkboxUI元素:

https://github.com/Brayden/UICheckbox

我喜欢阿德里安的想法,使用字符,而不是图像。 但是我不喜欢这个盒子,它只需要勾选标记(@“\ u2713”)。 我以编程方式绘制一个框(圆angular框),并将一个UILabel包含其中的复选标记。 这种实现方式可以轻松地在任何应用程序中使用自定义视图,而不必关心任何依赖资源。 您还可以自定义复选标记的颜色,圆angular框和背景。 以下是完整的代码:

 #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]; } } } 

在.h文件中

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

和.m文件

 - (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"]; } } 

这将做的伎俩…

我用UITextField做了这个,以避免画出任何奇怪的东西,但是我喜欢把NSString:@“\ u2713”作为文本标记在unicode中(Unicode字符'CHECK MARK'(U + 2713))。

这样,在我的.h文件(实现UITextField'UITextFieldDelegate'的协议):

 UITextField * myCheckBox; 

在我的viewDidLoad或者准备UI的函数中:

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

然后,添加一个事件select器来触发touch事件并调用“responseSelected”事件:

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

最后回应那个select器

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

函数“isChecked”只检查文本是否为@“\ u2713”复选标记。 为了防止在select文本字段时显示键盘,使用UITextField的“textFieldShouldBeginEditing”事件并添加事件select器来pipe理select:

 -(BOOL)textFieldShouldBeginEditing:(UITextField *)textField { // Question selected form the checkbox [self checkboxSelected]; // Hide both keyboard and blinking cursor. return NO; } 

子类UIButton,放下一个button,以查看控制器,select它,并将类名更改为身份检查器中的checkbox。

 #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 

用户Aruna Lakmal; 仅供参考,当您将此代码添加到IB时,如您所描述的initWithFrame未被调用,initWithCoder为。 实现initWithCoder,它会像你描述的那样工作。