IOS 自定义复选框

1、首先创建工程文件,CheckBox,

然后创建CheckBox类,继承自UIView,同时添加资源文件,选中、取消的图片,添加完成以后目录如下:

IOS 自定义复选框_第1张图片

CheckBox类头文件代码如下:

#import 

@protocol CheckBoxDelegate;

@interface CheckBox : UIView

@property(nonatomic,retain)NSString *text;//显示文字
@property(nonatomic,assign)BOOL checked;//是否选中

@property(nonatomic,retain) id delegate;//代理

-(id)initWithText:(NSString *)text frame:(CGRect)frame;//初始化

@end

@protocol CheckBoxDelegate

-(void)onChangeDelegate:(CheckBox *)checkbox isCheck:(BOOL)isCheck;

@end

CheckBox实现代码如下:

#import "CheckBox.h"
@interface CheckBox()

@property(nonatomic,retain)UIImage *onImage;
@property(nonatomic,retain)UIImage *offImage;

@end


@implementation CheckBox

-(void)dealloc{
    [_text release];
    [_delegate release];
    [_onImage release];
    [_offImage release];
    [super dealloc];
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
-(id)initWithText:(NSString *)text frame:(CGRect)frame{
    self=[super initWithFrame:frame];
    if(self){
        _text=text;
        self.backgroundColor=[UIColor clearColor];
        self.onImage=[UIImage imageNamed:@"chk_on.png"];//选中图片
        self.offImage=[UIImage imageNamed:@"chk_off.png"];//取消图片
    }
    return self;
}
-(void)setChecked:(BOOL)checked{
    _checked=checked;
    //注册代理事件,通知状态改变
    if([self.delegate respondsToSelector:@selector(onChangeDelegate:isCheck:)]){
        [self.delegate onChangeDelegate:self isCheck:_checked];
    }
    
    [self setNeedsDisplay];
}
-(void)drawRect:(CGRect)rect{//将text,image绘制到UIView上面
    UIImage *image=self.checked?self.onImage:self.offImage;
    [image drawAtPoint:CGPointMake(5, 8)];
    UIFont *font=[UIFont systemFontOfSize:16.0f];
    [self.text drawAtPoint:CGPointMake(25, 8) withFont:font];
}
//点击事件
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    self.checked=!self.checked;
}


@end

调用代码如下:首先引入CheckBox,

#import "ViewController.h"
#import "CheckBox.h"

@interface ViewController ()
<
CheckBoxDelegate//协议
>


@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    CheckBox *cb=[[CheckBox alloc] initWithText:@"乒乓球" frame:CGRectMake(10, 10, 80, 30)];
    cb.delegate=self;//设置委托
    [self.view addSubview:cb];
    [cb release];
    
}
-(void)onChangeDelegate:(CheckBox *)checkbox isCheck:(BOOL)isCheck{//
    NSLog(@"text:%@,State:%@",checkbox.text,isCheck?@"YES":@"NO");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end



你可能感兴趣的:(IOS)