IOS开发教程自定义CheckBox控件.docx
文本预览下载声明
首先创建工程文件,CheckBox,然后创建CheckBox类,继承自UIView,同时添加资源文件,选中、取消的图片,添加完成以后目录如下:CheckBox类头文件代码如下:#import UIKit/UIKit.h??@protocol CheckBoxDelegate;???@interface CheckBox : UIView??@property(nonatomic,retain)NSString *text;//显示文字??@property(nonatomic,assign)BOOL checked;//是否选中???@property(nonatomic,retain) idCheckBoxDelegate delegate;//代理???-(id)initWithText:(NSString *)text frame:(CGRect)frame;//初始化???@end???@protocol CheckBoxDelegateNSObject??-(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 ()???CheckBoxDele
显示全部