美文网首页UI杂记
UILabel:文字到边缘的距离

UILabel:文字到边缘的距离

作者: T_Choues | 来源:发表于2021-01-15 15:53 被阅读0次

    UILabel不像别的UI控件,可以通过设置edgeInset属性来控制文字、图片与边缘的距离。
    但是我们可以通过自定义Label,重写drawTextInRect的方式来实现。

    核心代码:

    - (void)drawTextInRect:(CGRect)rect {
        [super drawTextInRect:UIEdgeInsetsInsetRect(rect, _textInsets)];
    }
    

    通过添加属性值textInsets,达到动态控制的效果。

    完整代码参考

    头文件:

    #import <UIKit/UIKit.h>
    
    @interface KDOHLabel : UILabel
    
    @property (nonatomic, assign) UIEdgeInsets textInsets;
    
    @end
    

    实现文件:

    #import "KDOHLabel.h"
    
    @implementation KDOHLabel
    
    - (instancetype)init {
        if (self = [super init]) {
            _textInsets = UIEdgeInsetsZero;
        }
        return self;
    }
    
    - (instancetype)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            _textInsets = UIEdgeInsetsZero;
        }
        return self;
    }
    
    - (instancetype)initWithCoder:(NSCoder *)aDecoder {
        if (self = [super initWithCoder:aDecoder]) {
            _textInsets = UIEdgeInsetsZero;
        }
        return self;
    }
    
    #pragma mark - Override
    
    - (void)drawTextInRect:(CGRect)rect {
        [super drawTextInRect:UIEdgeInsetsInsetRect(rect, _textInsets)];
    }
    
    @end
    

    相关文章

      网友评论

        本文标题:UILabel:文字到边缘的距离

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