iOS Developer收藏iOS 知识点

iOS UIButton图片文字位置调整

2018-01-02  本文已影响636人  calary

前言

在平时的开发中我们经常会碰到图片配合文字的情况(如下图),而控件UIButton默认是左图右字,如果想实现下面的效果我们就要进行一些处理


样式展示

UIButton扩展

这里主要用到了两个属性

@property(nonatomic) UIEdgeInsets titleEdgeInsets; // default is UIEdgeInsetsZero  
@property(nonatomic) UIEdgeInsets imageEdgeInsets; // default is UIEdgeInsetsZero

原理详解参考调整UIButton的title和image详解

问题总结

//计算字体的大小,如果titleLabel的宽度小于字体的宽度,则是没显示全,给label宽度赋值
CGSize textSize = [self.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:self.titleLabel.font}];
CGSize frameSize = CGSizeMake(ceilf(textSize.width), ceilf(textSize.height));
if (labWidth < frameSize.width) {
        labWidth = frameSize.width;
 }
    UIButton *btn4 = [[UIButton alloc] init];
    [btn4 setImage:[UIImage imageNamed:@"tab_me"] forState:UIControlStateNormal];
    [btn4 setTitle:@"首页" forState:UIControlStateNormal];
    [btn4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    btn4.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:btn4];
    [btn4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(60);
        make.left.offset(50);
        make.top.mas_equalTo(btn3.mas_bottom).offset(20);
    }];
    [btn4 layoutWithStatus:MCLayoutStatusImageBottom andMargin:3];

传送门

最后附上demo地址,将分类拷贝到项目中即可使用,如果对你有用的话请给不要吝啬你的star✨哦。

上一篇下一篇

猜你喜欢

热点阅读