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阅读 174,950评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,191评论 4 61
  • ——真实的科大,真实的风云 前25年,人生中的三大导师,何兄为其一。父母养育之恩,教我独立:李老师叫我学习之道,从...
    小鱼儿的眼睛阅读 3,550评论 0 2
  • 上期我们结束了对秋水主线——河神海神的探讨。但是秋水可不仅仅只有这一条主线,更有几条支线。而且更有意思的是,这几条...
    散翎阅读 3,928评论 0 3