关于UIButton里面带有图片的研究

<span style="color:#3333ff;">如果一个Button里面带有图片,基本上我们用到有两种情况,一种是文字在左图片在右,一种是图片在左文字在右,针对这两种情况我们一般是可以设置UIButton的
setImageEdgeInsets属性,但是这样去改变有时候会很麻烦,所以我的入手点变为重写Button的方法。</span>

<span style="color:#ff0000;">一、图片在文字左边的情况:</span>
#define ButtonTitleFont [UIFont systemFontOfSize:14]

@implementation OKWMyButton

- (id)initWithFrame:(CGRect)frame

{
    
    self = [superinitWithFrame:frame];
    
    if (self) {
        
        <span style="color:#009900;">//可根据自己的需要随意调整</span>
        
        self.titleLabel.textAlignment =NSTextAlignmentLeft;
        
        self.titleLabel.font =ButtonTitleFont;
        
        self.imageView.contentMode =UIViewContentModeScaleAspectFit;
        
    }
    
    returnself;
    
}

<span style="color:#009900;">//重写父类UIButton的方法

//更具button的rect设定并返回文本label的rect</span>

- (CGRect)titleRectForContentRect:(CGRect)contentRect

{
    
    CGFloat titleW = contentRect.size.width-30;
    
    CGFloat titleH = contentRect.size.height;
    
    CGFloat titleX =30;
    
    CGFloat titleY =0;
    
    contentRect = (CGRect){{titleX,titleY},{titleW,titleH}};
    
    return contentRect;
    
}

<span style="color:#009900;">//更具button的rect设定并返回UIImageView的rect</span>

- (CGRect)imageRectForContentRect:(CGRect)contentRect

{
    
    CGFloat imageW =20;
    
    CGFloat imageH =20;
    
    CGFloat imageX =5;
    
    CGFloat imageY =12;
    
    contentRect = (CGRect){{imageX,imageY},{imageW,imageH}};
    
    return contentRect;
    
}


<span style="color:#ff0000;">二、图片在文字右边</span>
#define ButtonTitleFont [UIFont systemFontOfSize:14]

@implementation OKWMyImageRightButton

- (id)initWithFrame:(CGRect)frame

{
    
    self = [superinitWithFrame:frame];
    
    if (self) {
        
        <span style="color:#009900;">//可根据自己的需要随意调整</span>
        
        self.titleLabel.textAlignment =NSTextAlignmentRight;
        
        self.titleLabel.font =ButtonTitleFont;
        
        self.imageView.contentMode =UIViewContentModeScaleAspectFit;
        
    }
    
    returnself;
    
}

<span style="color:#009900;">//重写父类UIButton的方法

//更具button的rect设定并返回文本label的rect</span>

- (CGRect)titleRectForContentRect:(CGRect)contentRect

{
    
    CGFloat titleW = contentRect.size.width-24;
    
    CGFloat titleH = contentRect.size.height;
    
    CGFloat titleX =0;
    
    CGFloat titleY =0;
    
    contentRect = (CGRect){{titleX,titleY},{titleW,titleH}};
    
    return contentRect;
    
}

<span style="color:#009900;">//更改button的rect设定并返回UIImageView的rect</span>

- (CGRect)imageRectForContentRect:(CGRect)contentRect

{
    
    CGFloat imageW =5;
    
    CGFloat imageH =10;
    
    CGFloat imageX = contentRect.size.width-24;
    
    CGFloat imageY =15;
    
    contentRect = (CGRect){{imageX,imageY},{imageW,imageH}};
    
    return contentRect;
    
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章