重写uibutton,文字在左,图片在右,文字和图片居中

新建一个继承自UIButton的类,在.m文件中重写下面方法

- (id)initWithFrame:(CGRect)frame

{

    self= [superinitWithFrame:frame];

    if(self)

    {

        self.titleLabel.textAlignment = NSTextAlignmentCenter;

        self.imageView.contentMode = UIViewContentModeCenter;

    }

    return self;

}

- (CGRect)titleRectForContentRect:(CGRect)contentRect

{

    // 文字的最大尺寸

    CGSizemaxSize =CGSizeMake(MAXFLOAT, contentRect.size.height);

    // 计算文字的高度

    CGFloat titleW = [self.currentTitle boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15*ScalePluse]} context:nil].size.width;

    CGFloattitleX = (contentRect.size.width-titleW-13)/2.0;

    CGFloattitleY =0;

    CGFloat titleH = self.frame.size.height;

    returnCGRectMake(titleX, titleY, titleW, titleH);

}

- (CGRect)imageRectForContentRect:(CGRect)contentRect

{

    //标题的内容

    // 文字的最大尺寸

    CGSizemaxSize =CGSizeMake(MAXFLOAT, contentRect.size.height);

    // 计算文字的高度

    CGFloat titleW = [self.currentTitle boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15*ScalePluse]} context:nil].size.width;

    CGFloattitleX = (contentRect.size.width-titleW-13)/2.0;

    CGFloatimageX = titleW+titleX+3;

    CGFloatimageY =0;

    CGFloat imageH = self.frame.size.height;

    CGFloatimageW =10;

    returnCGRectMake(imageX, imageY, imageW, imageH);

}

你可能感兴趣的:(重写uibutton,文字在左,图片在右,文字和图片居中)