自定义按钮UIControl

写在前面

#图标和文字在一起是开发难免的问题,系统的按钮默认是图片居左的文字居右的,
且图片和文字的距离不好调整,图片的位置更是让人头疼,
故在闲暇之余封装了一个控件。
复制代码

所用到知识的

# 1、苹果系统自带的自动布局,减少第三方的依赖
# 2、kvo监听UIControl的状态
# 3、富文本的使用,如何更新约束,如何获取一段文字的宽高复制代码

先看看效果

拥有功能

1、任意调整图片和文字的间距。
2、图片的位置可以放置在上下左右不同位置。
3、支持富文本,自定义布局,高亮和选中状态。
复制代码

如何使用

/**自定义按钮初始化方法@param image 默认的图片@param title 标题@param titleFond 标题大小@param imageMargin 标题与图标的距离@param imageAlignmentTYpe 图片的显示类型@return 自定义按钮的实例*/
- (instancetype)initWithImage:(UIImage  *) imagetitle:(NSString *) titletitleFond:(UIFont *)   titleFondimageMargin:(CGFloat)    imageMarginimageAlignmentTYpe:(MyButtonImageAlignmentTYpe )imageAlignmentTYpe;_myButton = [[MyButton alloc]initWithImage:[UIImage imageNamed:@"cache_pause"]title:@"来点我啊"titleFond:[UIFont systemFontOfSize:14]imageMargin:10imageAlignmentTYpe:MyButtonImageAlignmentLeft];[self.view addSubview:_myButton];self.myButton.frame = CGRectMake(20, 100, 120, 40);self.myButton.backgroundColor = UIColor.grayColor;[self.myButton setImage:[UIImage imageNamed:@"cache_delete"] withState:UIControlStateSelected];[self.myButton setImage:[UIImage imageNamed:@"cache_pause"] withState:UIControlStateHighlighted];[self.myButton setTitle:@"选中了" withState:UIControlStateSelected];[self.myButton setTitle:@"正在按下..." withState:UIControlStateHighlighted];[self.myButton setTitleColor:UIColor.blueColor withState:UIControlStateSelected];[self.myButton setTitleColor:UIColor.yellowColor withState:UIControlStateHighlighted];这样就可以了,和普通的按钮用法一样。复制代码

关键代码

1、自定义布局(只列出了一种)
//图片居左
- (void)setImageLeftLayoutConstraint {CGFloat imageWidth  = self.normalImage.size.width;CGFloat titleWidth = [self sizeWithText:self.titleLabel.text font:self.titleLabel.font].width;CGFloat imageCenterXMargin = (imageWidth /2.0 - (imageWidth + titleWidth + self.imageMargin) / 2.0);//创建Image约束NSLayoutConstraint *imageCenterYLc = [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];NSLayoutConstraint *imageCenterXLc = [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:imageCenterXMargin];[self addConstraints:@[imageCenterYLc,imageCenterXLc]];//创建title约束NSLayoutConstraint *titleCenterYLc = [NSLayoutConstraint constraintWithItem:self.titleLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];NSLayoutConstraint *titleLeftLc = [NSLayoutConstraint constraintWithItem:self.titleLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.imageView attribute:NSLayoutAttributeRight multiplier:1.0 constant:self.imageMargin];[self addConstraints:@[titleCenterYLc,titleLeftLc]];
}//获取文字的宽高
- (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font {NSDictionary *attrs = @{NSFontAttributeName : font};return [text boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}//kvo监听
- (void)addObserver {[self addObserver:selfforKeyPath:@"enabled"options: NSKeyValueObservingOptionNewcontext:nil];[self addObserver:selfforKeyPath:@"selected"options: NSKeyValueObservingOptionNewcontext:nil];[self addObserver:selfforKeyPath:@"highlighted"options: NSKeyValueObservingOptionNewcontext:nil];[self.titleLabel addObserver:selfforKeyPath:@"text"options:NSKeyValueObservingOptionNewcontext:nil];
}//kvo 监听处理(只列出了部分)
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {if ([keyPath isEqualToString:@"selected"]) {if(self.selected) {self.imageView.image           = self.selectedImage ? self.selectedImage : self.normalImage;self.backgroundColor           = self.selectedBackgroundColor  ? self.selectedBackgroundColor : self.normalBackgroundColor;if (!self.selectedTitleAttribute && !self.normalTitleAttribute) {self.titleLabel.text       = self.selectedTitle ? self.selectedTitle : self.normalTitle;self.titleLabel.textColor  = self.selectedTitleColor ? self.selectedTitleColor : self.normalTitleColor;return;}self.titleLabel.attributedText = self.selectedTitleAttribute ? self.selectedTitleAttribute : self.normalTitleAttribute;} else {self.imageView.image           = self.normalImage;self.backgroundColor           = self.normalBackgroundColor;if (!self.normalTitleAttribute) {self.titleLabel.text       = self.normalTitle;self.titleLabel.textColor  = self.normalTitleColor;return;}self.titleLabel.attributedText = self.normalTitleAttribute;}} //监听到字体变化,更新自动布局if ([keyPath isEqualToString:@"text"]) {[self removeConstraints:self.constraints];[self.superview layoutIfNeeded];[self updateConstraints:self.imageAlignmentTYpe];[self.superview layoutIfNeeded];}
复制代码

以上只是部分代码,详细代码请查看

欢迎查看MyApp

自定义按钮 https://github.com/dudongge/MyApp

如果对您有帮助,请不吝star一下

自定义按钮 图片标题位置随意放置相关推荐

  1. 【ucGUI如何在对话框的标题栏中新增自定义按钮】

    ucGUI如何在对话框的标题栏中新增自定义按钮 对话框中可以新增的按钮 在标题栏加入自定义按钮 本文章基于ucGUI3.98版本而言,因为公司不让升级版本,版本变动会带来很多麻烦,因此基于旧版本实现一 ...

  2. 【iOS开发-8】UIButton类型属性简单归纳以及自定义按钮的设置

    (1)UIButton类继承自UIControl,而UIControl继承自UIView,因为UIView就是个矩形区域,所以UIButton实例化的对象其实都是一个矩形,虽然有各种圆角.增加联系人. ...

  3. Unity之手机键盘自定义输入栏位置适配不同手机分辨率适配

    Unity之手机键盘自定义输入栏位置适配&不同手机分辨率适配 效果图 PC端展示 手机端展示(手机是顶部带摄像头的IQOO Neo 5 ) 设计思路 也没啥思路不思路的,就是获取键盘高度,在安 ...

  4. 【UE4教程】Unreal 4.22 CustomButton 自定义按钮点击范围 异形按钮

    UE4 CustomButton 自定义按钮点击范围 异形按钮 相信大家都有见过游戏内的环形菜单,或者奇形怪状的按钮,但是UE4内的按钮只有方形的,就算做成环形或者异形菜单的样子,依然会出现点击空白处 ...

  5. 自定义按钮动态变化_新闻价值的变化定义

    自定义按钮动态变化 I read Bari Weiss' resignation letter from the New York Times with some perplexity. In par ...

  6. ueditor工具栏弹出html,UEditor工具栏上自定义按钮、图标、事件、窗口页面

    第一步:找到editor_config.js(或者ueditor.config.js)文件中的toolbars参数,增加一个"camnpr"字符串,对应着添加一个labelMap, ...

  7. UEditor工具栏上自定义按钮、图标、事件、窗口页面

    2019独角兽企业重金招聘Python工程师标准>>> 第一步:找到editor_config.js(或者ueditor.config.js)文件中的toolbars参数,增加一个& ...

  8. ODOO13 有同志留言,想看看QWEB渲染widget实现自定义按钮。今天,他来撩

    有同志留言,想看看Widget实现自定义按钮.今天,他来撩. Odoo生态系统的一个常见需求是从外部扩展/更改基本系统的行为(通过安装应用程序,即不同的模块).例如,可能需要在某些视图中添加新的小部件 ...

  9. 鼠标图标怎么自定义_苹果ios14怎么自定义图标 图标位置自由排列换风格教程

    苹果ios14怎么自定义图标 图标位置自由排列换风格教程 iOS 14 发布后,自定义主屏幕图标成为了一种流行的趋势,一些用户通过「快捷指令」将默认的应用图标替换为自定义图标,然后将应用本来的图标隐藏 ...

最新文章

  1. ToString()、Convert.ToString()、(string)、as string 的区别
  2. getRealPath(““)与getRealPath(“/“)区别及用法——计算机网络相关学习笔记
  3. Objective-C( Foundation框架 一 常见的结构体)
  4. Kafka 日志消息保存时间
  5. 运维 xshell 学习
  6. {Unity} iOS 9 字体的坑
  7. 加油站管理系统前五排行榜
  8. [XP虚拟机安装]VMware安装XP虚拟机
  9. 激活mircrosoft office2013
  10. 设计师网页导航 php,设计师必须收藏的7个网址导航
  11. 如何掌握电烙铁焊接技术
  12. CDN加速的作用以及APP被渗透入侵的解决方案
  13. 互作转录组常用数据库介绍
  14. 优酷视频怎么转二维码_优酷视频转二维码
  15. Python密度和轮廓图绘制--Matplotlib详解
  16. 解决Microsoft Office SDX Helper服务占用率高
  17. 通用爬取文章及图片导出到Word主程序代码
  18. ideapad720s在接通电源情况下,关机后自动重启的解决办法
  19. 关于ListView的删除刷新列表
  20. 自动化测试之 web - 基础篇

热门文章

  1. Python reload 函数 - Python零基础入门教程
  2. mysql从服务器配置_mysql主从服务器配置基础教程
  3. bellman ford java_Java C 实现Bellman-ford算法
  4. android listview countdowntimer,Android-ListView中的CountDownTimer随机闪烁
  5. JAVA awt eventqueue_线程“AWT-EventQueue-1”中的异常java.lang.NullPointerException
  6. oracle 插入一个语句,oracle如何通过1条语句插入多个值 oracle通过1条语句插入多个值方法...
  7. html 图片行内剧中,HTML入门(转义字符、行内样式和块级元素、定位、锚点、跑马灯标签、图片标签、表格标签的讲解)...
  8. 数字摄像头测试软件,图像测量软件(Camera Measure)
  9. #控制台大学课堂点名问题_你对大学生活的5大误解!看完我想静静......
  10. 利用STM32制作红外测温仪之软件设计(MLX90614)