IOS中沒有checkbox和radio button ,這一點對於做過android的童鞋會覺得挺無語的,沒關系,我們自己寫一個view來實現自己的單、復選框。
首先在你的資源裡面添加2張圖片,一張為按鈕的選中狀態,另一個為沒選中狀態,分別命名:unchecked.png,checked.png,下面上代碼,相信你看得懂。,如有疑問,歡迎留言交流。
UICheckBox.h
[cpp]
01.#import <UIKit/UIKit.h>
02.
03.@interface UICheckBox : UIButton
04.
05.@end
#import <UIKit/UIKit.h>
@interface UICheckBox : UIButton
@endUICheckBox.m
[cpp]
01.#import "UICheckBox.h"
02.
03.@implementation UICheckBox
04.
05.- (id)initWithFrame:(CGRect)frame
06.{
07. self = [super initWithFrame:frame];
08. if (self) {
09. [self setBackGroundImage];
10. }
11. return self;
12.}
13.- (void)setBackGroundImage {
14. [self setBackgroundImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
15. [self setBackgroundImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateSelected];
16. [self addTarget:self action:@selector(touchUIInside:) forControlEvents:UIControlEventTouchUpInside];
17.}
18.
19.-(id)initWithCoder:(NSCoder *)aDecoder{
20. self = [super initWithCoder:aDecoder];
21. if (self) {
22. [self setBackGroundImage];
23. }
24. return self;
25.}
26.
27.-(IBAction)touchUIInside:(id)sender{
28. UICheckBox* cb= (UICheckBox*)sender;
29. cb.selected = !cb.selected;
30.
31.}