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

自定义一个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.代码是经过删减的,大家关键是重写上面的两个方法,重新绘制矩形,即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值