美文网首页
UIButton垂直布局(上图+下字)

UIButton垂直布局(上图+下字)

作者: Hardy_Hu | 来源:发表于2017-03-23 18:55 被阅读0次

UIButton在开发中经常使用,默认布局是左image右title,实际开发中常常需要上image下title,显然默认的样式不能满足我们的需求。之前我使用titleEdgeInsets和imageEdgeInsets去调整,如下:

 CGFloat w =  [UIScreen mainScreen].bounds.size.width /4;
 [but setImageEdgeInsets:UIEdgeInsetsMake(0, w / 3, 30, w / 3)];
 [but setTitleEdgeInsets:UIEdgeInsetsMake(50, -image.size.width, 0, 0)];

感觉很不爽,每个button都需要重复的代码,敲的真很心累!

一直以来总想找到一个比较懒的方法,一次封装,永久调用。功夫不负有心人,今天总算找到了一个API,可以实现,窃喜。

- (instancetype)initWithFrame:(CGRect)frame
- (CGRect)imageRectForContentRect:(CGRect)contentRect

我们需要自己写一个类,继承于UIButton。 由于是上图片下文字结构的布局,故命名为HTVerticalButton,在HTVerticalButton.m文件中直接改写UIButton的方法,如下:

- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    CGFloat titleY = contentRect.size.height *0.6;
    CGFloat titleW = contentRect.size.width;
    CGFloat titleH = contentRect.size.height - titleY;
    return CGRectMake(0, titleY , titleW, titleH);
}
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGFloat imageW = CGRectGetWidth(contentRect);
    CGFloat imageH = contentRect.size.height * 0.6;
    return CGRectMake(0, 0, imageW, imageH);
}

发现基本上实现了我们的需求,唯有文字没有居中对齐,故还需要设置文字的居中对齐方式,本着只想一次修改的目的,我还是在HTVerticalButton.m中设置。

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return self;
}

运行下,基本解决了我们的需求。
使用时只需要导入我们自定义的类#import "HTVerticalButton.h"即可

- (void)setupUI
{
    CGFloat w = self.bounds.size.width / 5;
    CGFloat h = self.bounds.size.height / 2;
    for (int i = 0; i<10; i++)
    {
        HTVerticalButton *but =[HTVerticalButton buttonWithType:UIButtonTypeCustom];
        but.frame = CGRectMake(i%5 * w, i/5 * h, w, h);
        [but setTitle:@"按钮" forState:UIControlStateNormal];
        [but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [but setImage:[UIImage imageNamed:@"shape-127"] forState:UIControlStateNormal];
        but.backgroundColor = [UIColor redColor];
        but.layer.masksToBounds = YES;
        but.layer.cornerRadius = 5;
        [self addSubview:but];
    }
}

这样就像使用系统UIButton方法样,直接设置title和image后,再也不需要设置EdgeInsets,不用去关心布局问题了。

HTVerticalButton.png

注意下:

  1. 如果需要重写系统的方法,可以自己写个类继承系统类,然后在.m文件中直接写你的实现,无需在.h文件中再次声明此方法。
  2. 重写系统方法时,不可以使用类别,会报警告的。

相关文章

网友评论

      本文标题:UIButton垂直布局(上图+下字)

      本文链接:https://www.haomeiwen.com/subject/eprtottx.html