自定义UIButton--iPhone按钮控件点击效果写法

当我们自定义了一个UIButton时,如果采用重绘的方式,将drawRect事件重写了,原有自带的点击的效果就没有了,这时,我们也要自己来重新写的。 例如下面效果的按钮 UIButton 自定义 @implementation WeiboButton @synthesize iconFile,title; - (id) initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { [self addObserver:self forKeyPath:@"highlighted" options:0 context:nil]; //增加对highlighted属性的观察 } return self; } -(void)dealloc { [self removeObserver:self forKeyPath:@"highlighted"];//移除对highlighted属性的观察 [super dealloc]; } -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"highlighted"]) { [self setNeedsDisplay];//当按钮被按下时,重绘按钮 } } -(void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGRect buttonRect=self.bounds; //画背景 CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]); CGContextFillRect(context, buttonRect); //画边框 CGContextSetLineWidth(context, 1.0); CGContextSetStrokeColorWithColor(context,[[UIColor lightGrayColor] CGColor]); CGContextStrokeRect(context, buttonRect); //画图标 if (_iconFile !=nil && ![_iconFile isEqualToString:@""]) { UIImage * iconImage=[UIImage imageNamed:_iconFile]; [iconImage drawInRect:CGRectMake(10, 10, 20, 20) ]; } //画文字 if (_title !=nil && ![_title isEqualToString:@""]) { //设置画笔线条粗细 CGContextSetLineWidth(context, 1.0); CGContextSetFillColorWithColor(context, [Setting_Cell_Text_Color_Common CGColor]); //设置字体 UIFont *font = [UIFont systemFontOfSize:15]; //在指定的矩形区域内画文字 CGRect textRect=CGRectMake(40, 10, self.bounds.size.width-40, 20); [_title drawInRect:textRect withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft]; } if ([self isHighlighted]) {//判断按钮是否被按下 [[UIColor lightGrayColor] set]; UIRectFillUsingBlendMode(rect, kCGBlendModeMultiply); } [super drawRect:rect]; } -(void)setIconFile:(NSString *)newIconFile { _iconFile=newIconFile; [self setNeedsDisplay]; } -(void)setTitle:(NSString *)newTitle { _title=newTitle; [self setNeedsDisplay]; } @end

posted on 2012-12-27 18:12  流れ星ーー  阅读(214)  评论(0编辑  收藏  举报

导航