iOS开发之UIButton
来源:互联网 发布:java qq2007.jar 编辑:程序博客网 时间:2024/04/29 19:49
本文主要是自定义UIButton,调整UIButton内部的文字和图标的位置(交换按钮和图标的位置)
新建一个继承自UIButton的类,在.m文件中实现UIButton自带的两个方法:titleRectForContentRect:和imageRectForContentRect:
来看一下正常的按钮样式:
下面开始自定义:
/** * 计算按钮文字的位置和尺寸 */- (CGRect)titleRectForContentRect:(CGRect)contentRect { CGFloat titleX = 0;// 文字的x坐标为0 CGFloat titleY = 0;// 文字的y坐标为0 CGFloat titleH = contentRect.size.height;// 文字的高度就等于按钮的高度 // 根据文字计算文字的宽度 NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; attrs[NSFontAttributeName] = [UIFont systemFontOfSize:16.0];// 字体 CGFloat titleW = [self.currentTitle boundingRectWithSize:CGSizeMake(MAXFLOAT, titleH) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size.width;// iOS7之后 return CGRectMake(titleX, titleY, titleW, titleH);}/** * 计算按钮图标的位置和尺寸 */- (CGRect)imageRectForContentRect:(CGRect)contentRect { // 图标的宽度 CGFloat imageH = contentRect.size.height;// 图标的高度就等于按钮的高度 CGFloat imageW = imageH; CGFloat imageX = contentRect.size.width - imageH;// 图标的x坐标 CGFloat imageY = 0;// 图标的y坐标为0 return CGRectMake(imageX, imageY, imageW, imageH); }接下来就是根据需要对按钮内部的文字和图标进行微调
// 如果按钮是从xib文件中加载的- (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { [self setup]; } return self;}// 如果是用代码创建按钮- (instancetype)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { [self setup]; } return self;}/** * 初始化方法 */- (void)setup { // 设置图片居中 self.imageView.contentMode = UIViewContentModeCenter; // 按钮文字的字体一定要和计算的时候相同 self.titleLabel.font = [UIFont systemFontOfSize:16.0]; // 高亮时不需要调整图片 self.adjustsImageWhenHighlighted = NO;}运行之后按钮就变成这样的了:
这样的按钮通常情况下都是显示在导航栏的标题中。
按钮的高亮状态会让按钮变的灰灰的,有时候我们需要取消按钮的高亮状态,这个时候我们需要重写setHighlighted:方法来覆盖父方法。
// 重写方法,覆盖父方法,取消按钮的高亮状态- (void)setHighlighted:(BOOL)highlighted { }这样即可取消按钮的高亮状态。
0 0
- IOS开发之UIButton
- IOS开发之UIButton
- iOS开发之UIButton
- iOS开发之UIButton
- iOS开发之UIButton
- IOS开发之UIButton详解
- iOS 开发之设置UIButton
- IOS开发之uibutton透明
- IOS开发之UIButton详解
- iOS开发之 UILabel,UIButton
- IOS界面开发之UIButton
- IOS开发(16)之UIButton控件
- iOS 开发之设置UIButton(温故知新)
- IOS 开发之设置UIButton的title
- IOS 开发之设置UIButton的title
- IOS 开发之设置UIButton的title
- IOS 开发之设置UIButton的title
- IOS 开发之设置UIButton的title
- libevent源码解析------日志和错误处理
- final
- 【Leetcode】Remove Duplicates from Sorted Array
- Stall Reservations
- 【论文笔记】T-Finder-A Recommender System for Finder Passengers and vacant Taxis
- iOS开发之UIButton
- git 命令使用
- ArrayList利用泛型对象操作
- 关于spring 3.2 @scheduled cron的
- c语言基础知识
- c3p0.properties
- Codeforces Round #334 (Div. 2) B. More Cowbell
- 数据结构--向量--归并排序
- fzu2198 快来快来数一数