美文网首页
Button内部图片文字各种排版

Button内部图片文字各种排版

作者: 强子ly | 来源:发表于2019-02-25 21:36 被阅读11次

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

    #import <UIKit/UIKit.h>
    
    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
    

    相关文章

      网友评论

          本文标题:Button内部图片文字各种排版

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