#import@interface VCRoot : UIViewController@end#import "VCRoot.h"#import "ChechBox.h"@interface VCRoot ()@end@implementation VCRoot- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self;}- (void)viewDidLoad{ [super viewDidLoad]; //创建选择控件 ChechBox* checkBox = [[ChechBox alloc] initWithFrame:CGRectMake(100, 100, 30, 30)] ; //只显示父亲视图有效的范围,超过父亲视图的范围,剪切掉不显示 checkBox.clipsToBounds = YES ; checkBox.on = YES ; [checkBox addTarget:self action:@selector(checkAct) forControlEvents:UIControlEventValueChanged] ; [self.view addSubview:checkBox] ;}-(void) checkAct{ NSLog(@"点击选择控件!");}@end
#import//声明一个选择按钮//UIControl:可以响应事件的控件对象//UIControl:继承于UIView@interface ChechBox : UIControl{ //选中图片对象 UIImage* _imageSelect ; //取消选中图片对象 UIImage* _imageNoSelect ; //显示到视图上 UIImageView* _imageView ; //选中状态 BOOL _on ; //事件目标对象,当前控件的事件函数的拥有者对象 //_target:事件函数声明实现在对象中 //通常使用试图控器对象作为此值 id _target ; //事件函数对象(指针)声明 //用来响应响应的事件处理 //通过外部来赋值 //实现在外部,_target对象中实现 SEL _selector ;}//定义on属性@property (assign,nonatomic) BOOL on ;//重新定义setOn函数-(void) setOn:(BOOL)on ;//设置选中状态图片-(void) setSelectedImage:(UIImage*) image ;//设置取消状态的图片-(void) setNoSelectedImage:(UIImage*) image;//添加事件函数声明-(void) addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents ;@end#import "ChechBox.h"@implementation ChechBox- (id)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { // Initialization code //加载图片对象 _imageSelect = [UIImage imageNamed:@"selected"] ; _imageNoSelect = [UIImage imageNamed:@"noselected"] ; //创建视图 _imageView = [[UIImageView alloc] initWithImage:_imageNoSelect] ; //只能通过外部的参数设定位置 //不能设定控件的大小 _imageView.frame = CGRectMake(0, 0, 32, 32); _target = nil ; _selector = nil ; _on = NO ; [self addSubview:_imageView] ; } return self;}-(void) setSelectedImage:(UIImage *)image{ _imageSelect = image ; _imageView.image = _imageNoSelect ;}-(void) setNoSelectedImage:(UIImage *)image{ _imageNoSelect = image ; _imageView.image = _imageNoSelect ;}//添加设置事件函数-(void) addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents{// controlEvents == 0001100000// UIControlEventValueChanged== 1000000000// == 0000000000 if ((controlEvents &UIControlEventValueChanged) != 0) { _target = target ; _selector = action ; }}-(void) setOn:(BOOL)on{ //状态改变 if (_on != on) { _on = on ; if (_on == YES) { _imageView.image = _imageSelect ; } else if (_on == NO) { _imageView.image = _imageNoSelect ; } //respondsToSelector:target对象能否执行_selector函数 //功能:避免程序由于没有实现_selector,导致程序直接崩溃 //如果实现:返回值为YES if ([_target respondsToSelector:_selector] == YES) { //通过target action模式执行事件函数 [_target performSelector:_selector withObject:self afterDelay:0] ; } }}-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ self.on = !self.on ;}@end