美文网首页
iOS UILabel增加内边距属性

iOS UILabel增加内边距属性

作者: 打不死的强丿 | 来源:发表于2017-08-18 09:07 被阅读0次

    在某些场景我们想让Label像UIButton这种控件一样,可以设置内容边距,来使整体布局可拓展性增强。刚好项目中遇到需要使用的场景,就通过category为UILabel添加内边距属性。


    Demo下载:https://github.com/icofans/UIlabel-Insets


    .h

    @interface UILabel (Insets)

    /**

    和UIbutton相似,内边距属性

    控制字体与控件边界的间隙

    */

    @property (nonatomic, assign) UIEdgeInsets contentInsets;

    @end

    .m

    @implementation UILabel (Insets)

    static char kContentInsetsKey;

    static char kshowContentInsetsKey;

    - (void)setContentInsets:(UIEdgeInsets)contentInsets

    {

        objc_setAssociatedObject(self, &kContentInsetsKey, NSStringFromUIEdgeInsets(contentInsets), OBJC_ASSOCIATION_COPY_NONATOMIC);

        objc_setAssociatedObject(self, &kshowContentInsetsKey, @YES, OBJC_ASSOCIATION_COPY_NONATOMIC);

    }

    - (UIEdgeInsets)contentInsets

    {

        return UIEdgeInsetsFromString(objc_getAssociatedObject(self, &kContentInsetsKey));

    }

    + (void)load

    {

        [super load];

        // class_getInstanceMethod()

        Method fromMethod = class_getInstanceMethod([self class], @selector(drawTextInRect:));

        Method toMethod = class_getInstanceMethod([self class], @selector(tt_drawTextInRect:));

        // class_addMethod()

        if (!class_addMethod([self class], @selector(drawTextInRect:), method_getImplementation(toMethod), method_getTypeEncoding(toMethod))) {

            method_exchangeImplementations(fromMethod, toMethod);

        }

    }

    - (void)tt_drawTextInRect:(CGRect)rect

    {

        BOOL show = objc_getAssociatedObject(self, &kshowContentInsetsKey);

        if (show) {

            rect = UIEdgeInsetsInsetRect(rect, self.contentInsets);

        }

        [self tt_drawTextInRect:rect];

    }

    @end

    使用很简单

    textLabel.contentInsets = UIEdgeInsetsMake(0, 16, 0, 0);

    相关文章

      网友评论

          本文标题:iOS UILabel增加内边距属性

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