iOS 自定義按鈕(實現上圖下文字)

相信大家都或多或少的遇到過這樣的需求,網上有很多關于實現按鈕上圖下文字的介紹,使用UIEdgeInsetsMake()來改變按鈕文字和圖片的位置的方法居多。
下面我用一種簡單粗暴的自定義按鈕方法來實現該需求。

1、新建一個類,命名為“RYButton”,繼承“UIButton”。
(1)“RYButton.h”的內容如下:

#import <UIKit/UIKit.h>

@interface RYButton : UIButton

@property (nonatomic,strong) UIImageView *topImageView;

@property (nonatomic,strong) UILabel *bottomLable;

@end

(2)“RYButton.m”的內容如下:

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        self.topImageView = [[UIImageView alloc] init];
        self.topImageView.contentMode = UIViewContentModeScaleAspectFit;
        [self addSubview:self.topImageView];
        
        self.bottomLable = [[UILabel alloc] init];
        self.bottomLable.textColor =[UIColor lightGrayColor];
        self.bottomLable.textAlignment = NSTextAlignmentCenter;  //文字居中
        self.bottomLable.adjustsFontSizeToFitWidth = YES;   //文字大小自適應
        [self addSubview:self.bottomLable];

        //給按鈕添加邊框并設置邊框的顏色
        [self.layer setBorderWidth:1];
        CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
        CGColorRef color = CGColorCreate(colorSpaceRef, (CGFloat[]){0.9,0.9,0.9,1}); //RGB and alpha 
        [self.layer setBorderColor:color];
    }
    return self;
}

-(void)layoutSubviews {
    [super layoutSubviews];

    //在這里面可以設置按鈕的圖片和文字的尺寸
}

2、在需要此按鈕的類添加頭文件“RYButton.h”,并創建該按鈕。

RYButton *button = [RYButton buttonWithType:UIButtonTypeCustom];
button.frame = 你要設計的按鈕的尺寸;
[self.view addSubview:button];

在創建UILabel的時候,我建議一點。我一般會創建一個類,專門用來創建各種控件,然后在需要的時候調用即可。
比如我的代碼實現

self.bottomLable = [RYKitTool createLabelTextColor:[UIColor lightGrayColor] textAlignment:NSTextAlignmentCenter];
[self addSubview:self.bottomLable];

該類方法的實現為:

+(UILabel *)createLabelTextColor:(UIColor *)textColor textAlignment:(NSTextAlignment)textAlignment {
    UILabel *label = [[UILabel alloc] init];
    label.textColor = textColor;
    label.textAlignment = textAlignment;
    label.adjustsFontSizeToFitWidth = YES;
    return label;
}

這樣可以大大減少創建控件的代碼量,而且代碼重用也比較方便。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,132評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,214評論 4 61
  • ——真實的科大,真實的風云 前25年,人生中的三大導師,何兄為其一。父母養育之恩,教我獨立:李老師叫我學習之道,從...
    小魚兒的眼睛閱讀 551評論 0 2
  • 上期我們結束了對秋水主線——河神海神的探討。但是秋水可不僅僅只有這一條主線,更有幾條支線。而且更有意思的是,這幾條...
    散翎閱讀 674評論 0 3