自定义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

转载于:https://www.cnblogs.com/liuxingzi/archive/2012/12/27/3404303.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值