iOS - Button内部图文排版(超级好用)

  • Github下载地址

创建一个UIButton+Layout.h分类,支持Frame、Masonry,直接将代码粘出即可

#import 

NS_ASSUME_NONNULL_BEGIN

typedef NS_ENUM(NSUInteger, WJLayoutStatus){
    /** 正常位置,图左字右 */
    WJLayoutStatusNormal,
    /** 图右字左 */
    WJLayoutStatusImageRight,
    /** 图上字下 */
    WJLayoutStatusImageTop,
    /** 图下字上 */
    WJLayoutStatusImageBottom,
};

@interface UIButton (Layout)

- (void)layoutWithStatus:(WJLayoutStatus)status
               andMargin:(CGFloat)margin;

@end

NS_ASSUME_NONNULL_END
#import "UIButton+Layout.h"

@implementation UIButton (Layout)

- (void)layoutWithStatus:(WJLayoutStatus)status
               andMargin:(CGFloat)margin {
    CGFloat imgWidth = self.imageView.bounds.size.width;
    CGFloat imgHeight = self.imageView.bounds.size.height;
    CGFloat labWidth = self.titleLabel.bounds.size.width;
    CGFloat labHeight = self.titleLabel.bounds.size.height;
    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;
    }
    CGFloat kMargin = margin / 2.0;
    switch (status) {
        case WJLayoutStatusNormal: {
            [self setImageEdgeInsets:UIEdgeInsetsMake(0, -kMargin, 0, kMargin)];
            [self setTitleEdgeInsets:UIEdgeInsetsMake(0, kMargin, 0, -kMargin)];
        }
            break;
        case WJLayoutStatusImageRight: {
            [self setImageEdgeInsets:UIEdgeInsetsMake(0, labWidth + kMargin, 0, -labWidth - kMargin)];
            [self setTitleEdgeInsets:UIEdgeInsetsMake(0, -imgWidth - kMargin, 0, imgWidth + kMargin)];
        }
            break;
        case WJLayoutStatusImageTop: {
            [self setImageEdgeInsets:UIEdgeInsetsMake(0, 0, labHeight + margin, -labWidth)];
            [self setTitleEdgeInsets:UIEdgeInsetsMake(imgHeight + margin, -imgWidth, 0, 0)];
        }
            break;
        case WJLayoutStatusImageBottom: {
            [self setImageEdgeInsets:UIEdgeInsetsMake(labHeight + margin,0, 0, -labWidth)];
            [self setTitleEdgeInsets:UIEdgeInsetsMake(0, -imgWidth, imgHeight + margin, 0)];
        }
            break;
        default:
            break;
    }
}

@end

你可能感兴趣的:(iOS - Button内部图文排版(超级好用))