博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
自定义UIButton--iPhone按钮控件点击效果写法
阅读量:7110 次
发布时间:2019-06-28

本文共 2070 字,大约阅读时间需要 6 分钟。

当我们自定义了一个UIButton时,如果采用重绘的方式,将drawRect事件重写了,原有自带的点击的效果就没有了,这时,我们也要自己来重新写的。 例如下面效果的按钮 @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

你可能感兴趣的文章
《Javascript高级程序设计 (第三版)》第三章 基本概念
查看>>
RhykeJS——专为开启“实验室功能”的手势密码库
查看>>
vue组件学习-数据传递-路由(初学者文档二)
查看>>
用ES6语法来开发angularjs项目,webpack进行按需加载模块打包
查看>>
可编程定时 / 计数器应用实验
查看>>
spring mvc中的几类拦截器对比
查看>>
Spring Security 使用总结
查看>>
Java验证
查看>>
一道CSS笔试题
查看>>
慕课网_《模式的秘密之单例模式》学习总结
查看>>
Struts2开发入门指南
查看>>
Ajax实现原理
查看>>
《深入理解ES6》笔记——解构:使数据访问更便捷(5)
查看>>
不再碎片化学习,快速掌握 H5 直播技术
查看>>
命令行神器推荐
查看>>
阿里云视频直播的相关准本工作(验签)
查看>>
2017-07-12 前端日报
查看>>
一个可供创业公司借鉴的持续集成技术实践
查看>>
PAI在线深度学习开发产品DSW发布
查看>>
Windows的Linux子系统搭建数据科学环境
查看>>