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

来源:互联网 发布:linq过滤重复数据 编辑:程序博客网 时间:2024/05/19 04:05

自定义一个button,要调整 button中的image(注意,不是backgroundImage) 和 title 文字的位置,只需要重写 Button类独对应的两个方法即可:

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

#import <UIKit/UIKit.h>@interface SuperButton : UIButton@end
实现文件#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.代码是经过删减的,大家关键是重写上面的两个方法,重新绘制矩形,即可

1 0
原创粉丝点击