您的位置:首页 > 移动开发 > IOS开发

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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: