您的位置:首页 > 其它

自定义button同时显示文字和图片

2016-06-20 10:23 323 查看
代码搬运工这样就可以实现图片和文字同时显示

首先创建一个继承于UIButton的类

//1. .h中这样写

#import <UIKit/UIKit.h>

@interface SHJF_Button :
UIButton

@end

//2. .m中这样写

#import "SHJF_Button.h"

@implementation SHJF_Button

重写init方法

- (instancetype)initWithFrame:(CGRect)frame

{

    self = [super
initWithFrame:frame];

    if (self) {

       
//可根据自己的需要随意调整

        

        self .
titleLabel . textAlignment =
NSTextAlignmentLeft ;

        

        self .
titleLabel . font =[
UIFont systemFontOfSize :
14.0 ];

        //        self . titleLabel . backgroundColor = [UIColor orangeColor];

        

        //        self . imageView . contentMode = UIViewContentModeLeft ;

    }

    return
self;

}

//重写父类UIButton的方法

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

- ( CGRect )titleRectForContentRect:(
CGRect )contentRect

{

    CGFloat titleW = myWidth/3/5*3
;

    

    CGFloat titleH = myHeight/100*3 ;

    

    CGFloat titleX = myWidth/3/5 ;

    

    CGFloat titleY = myHeight/100*12.4 ;

    

    

    

    contentRect = ( CGRect ){{titleX,titleY},{titleW,titleH}};

    

    return contentRect;

    

}

//更具button的rect设定并返回UIImageView的rect

- ( CGRect )imageRectForContentRect:(
CGRect )contentRect

{

    

    

    CGFloat imageW = myWidth/100*10 ;

    

    CGFloat imageH = myWidth/100*10 ;

    

    CGFloat imageX = myWidth/100*11.5 ;

    

    CGFloat imageY = myHeight/100*4.1 ;

    contentRect = ( CGRect ){{imageX,imageY},{imageW,imageH}};

    

    return contentRect;

    

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: