使用Auto Layout或layoutMargins为UILabel添加填充?

时间:2014-11-12 05:32:19

标签: ios uikit autolayout

我想在标签的框架及其文本之间添加插图。我可以使用layoutMarginshttp://carpeaqua.com/2014/07/24/auto-layout-in-ios-8-layout-margins/)进行此操作,但我无法做到这一点。

我有一个示例项目,您可以看到我在做什么(错误?):https://github.com/runmad/MessagingApp

enter image description here

1 个答案:

答案 0 :(得分:2)

如果我是你,我会继承UILabel并添加UIEdgeInsets。在UILabel的子类中,执行以下操作:

.m文件

    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];

        if (self){

             //Property in the header file so we can add custom insets per instance of this class 
                self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        }

        return self;
    }



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

/* So that it will also work with auto layout */ 
    -(CGSize)intrinsicContentSize
    {
        CGSize size = [super intrinsicContentSize];
        size.width += self.edgeInsets.left + self.edgeInsets.right;
        size.height += self.edgeInsets.top + self.edgeInsets.bottom;

        if (self.numberOfLines == 0){

             //There is a bug where intrinsice content
             //size may be 1 point too short

              size.height += 1;
           }

        return size;
    }