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

ios代码调整button图片image文字title位置

2016-03-11 18:32 363 查看


首先,我们来创建一个 SuperButton继承
UIButton

#import "SuperButton.h"
#import "UtilsFunctions.h"
@interface SuperButton ()
{
CGRect boundingRect;

}

@end

@implementation SuperButton
//自定义的初始化方法
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{

[self setTitle:@"项目介绍" forState:UIControlStateNormal];
[self.titleLabel setFont:[UIFont boldSystemFontOfSize:font]];
[self setBackgroundImage:[UIImage imageNamed:@"cpxq_shang@3x.png"] forState:UIControlStateNormal];
[self setImage:[UIImage imageNamed:@"cpxq_jiantou2@3x.png"] forState:UIControlStateNormal];
boundingRect=[self.titleLabel.text boundingRectWithSize:CGSizeMake(320,font) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil];
}
return self;
}
1.重写方法,改变 图片的位置  在  titleRect..方法后执行
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat imageX=self.frame.size.width/2+boundingRect.size.width/2;
UIScreen *s=[UIScreen mainScreen];
CGRect rect=s.bounds;
CGFloat imageY=contentRect.origin.y+14;
CGFloat width=24;
CGFloat height=24;
return CGRectMake(imageX, imageY, width, height);

}
2.改变title文字的位置,构造title的矩形即可
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{

CGFloat imageX=(self.frame.size.width-boundingRect.size.width)/2;
CGFloat imageY=contentRect.origin.y+10;
CGFloat width=220;
CGFloat height=25;
return CGRectMake(imageX, imageY, width, height);

}

@end
我们只要重写 上述的两个方法,就可以实现对  button按钮中的图片和文字的位置的调整
注意: 1.ios7和ios8系统上 上述两个方法 运行的次数会有差异,可以设置标志位,或者自定义一个 button(不要集成button)
2.代码是经过删减的,大家关键是重写上面的两个方法,重新绘制矩形,即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: