美文网首页iOS 适配
iOS 10 UILabel 内边距实现方法源码

iOS 10 UILabel 内边距实现方法源码

作者: 1b3bd36d9d21 | 来源:发表于2017-03-22 16:10 被阅读214次
    • .h头文件
    #import <UIKit/UIKit.h>
    
    @interface KeyImageLabel : UILabel
    
    @property(nonatomic, assign) UIEdgeInsets edgeInsets;
    
    @end
    
    • .m源文件
    #import "KeyImageLabel.h"
    
    @implementation KeyImageLabel
    
    - (instancetype)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            self.clipsToBounds = YES;
        }
        return self;
    }
    // 核心代码
    - (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
        UIEdgeInsets insets = self.edgeInsets;
        CGRect rect = [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, insets)
                        limitedToNumberOfLines:numberOfLines];
        
        rect.origin.x    -= insets.left;
        rect.origin.y    -= insets.top;
        rect.size.width  += (insets.left + insets.right);
        rect.size.height += (insets.top + insets.bottom);
        
        return rect;
    }
    // 核心代码
    - (void)drawTextInRect:(CGRect)rect {
        [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
    }
    
    /*
    - (void)layoutSubviews {
        [super layoutSubviews];
        self.layer.cornerRadius = self.frame.size.width / 2.0;
    }
    */
    @end
    
    • 使用方法
    KeyImageLabel *label = [[KeyImageLabel alloc] init];
    ......
    label.edgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    [self.view addSubView:label];
    

    相关文章

      网友评论

        本文标题:iOS 10 UILabel 内边距实现方法源码

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