iOS 自定义按钮
2015-11-25 01:06
225 查看
开发 app 过程我们经常需要自定义按钮;其实自定义按钮也简单的,废话少说直接上代码;
先创建一个类继承于 UIButton
#import <UIKit/UIKit.h>
@interface MyPlacebutton : UIButton
{
//定义button 的大小
CGRect boundingRect;
}
@end
//实现文件
//初始化自定义button单例
-(instancetype)initWithFrame:(CGRect)frame
{
self=[super initWithFrame:frame];
if (self) {
[self setTitle:@"" forState:UIControlStateNormal];
//设置默认的字体大小
[self.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
//获取button 的标题的占的空间大小
boundingRect=[self.titleLabel.text boundingRectWithSize:CGSizeMake(320,16) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil];
}
return self;
}
//1.重写方法,改变 图片的位置 在 titleRect..方法后执行 //调整图片的位置
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat imageX=5;
// UIScreen *s=[UIScreen mainScreen];
// CGRect rect=s.bounds;
CGFloat imageY=contentRect.origin.y+self.frame.size.height/2-10;
CGFloat width=20;
CGFloat height=20;
return CGRectMake(imageX, imageY, width, height);
}
//2.改变title文字的位置,构造title的矩形即可
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat imageX=30;
CGFloat imageY=4;
CGFloat width=self.frame.size.width-42;
CGFloat height=self.frame.size.height;
return CGRectMake(imageX, imageY, width, height);
}
先创建一个类继承于 UIButton
#import <UIKit/UIKit.h>
@interface MyPlacebutton : UIButton
{
//定义button 的大小
CGRect boundingRect;
}
@end
//实现文件
//初始化自定义button单例
-(instancetype)initWithFrame:(CGRect)frame
{
self=[super initWithFrame:frame];
if (self) {
[self setTitle:@"" forState:UIControlStateNormal];
//设置默认的字体大小
[self.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
//获取button 的标题的占的空间大小
boundingRect=[self.titleLabel.text boundingRectWithSize:CGSizeMake(320,16) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil];
}
return self;
}
//1.重写方法,改变 图片的位置 在 titleRect..方法后执行 //调整图片的位置
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat imageX=5;
// UIScreen *s=[UIScreen mainScreen];
// CGRect rect=s.bounds;
CGFloat imageY=contentRect.origin.y+self.frame.size.height/2-10;
CGFloat width=20;
CGFloat height=20;
return CGRectMake(imageX, imageY, width, height);
}
//2.改变title文字的位置,构造title的矩形即可
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat imageX=30;
CGFloat imageY=4;
CGFloat width=self.frame.size.width-42;
CGFloat height=self.frame.size.height;
return CGRectMake(imageX, imageY, width, height);
}
相关文章推荐
- iOS子线程操作检测版本更新,防止阻塞住线程
- iOS url 编码 解码
- iOS开发CoreAnimation解读之一——初识CoreAnimation核心动画编程
- ios 使用AVPlayer自定义视频播放器
- iOS 实现发送邮件和短信
- IOS开发遇到的绑定控件的问题
- 转 ios 里如何判断当前应用的定位服务是否可用
- iOS开发多线程-线程间的通信
- iOS ViewController之间传值方法五(使用block)
- IOS 实现不定参数方法
- IOS开发真机调试
- iOS-GCD多线程之dispatch_once
- iOS开发多线程-线程安全
- IOS开发打电话发短信发邮件
- ios 从系统相册选择多张图片
- iOS跳转到指定页面,而不是简单的返回上一个页面
- 图形变换之使用坐标变换
- iOS视图生命周期
- iOS单例的两种实现
- ios中nsdate与实际时间相隔八小时解决方案