2

I want to add inset between the label's frame and its text. I was under this was possible using layoutMargins (http://carpeaqua.com/2014/07/24/auto-layout-in-ios-8-layout-margins/) but I have no been able to do this.

I have a sample project where you can see what I am doing (wrong?): https://github.com/runmad/MessagingApp

enter image description here

runmad
  • 14,846
  • 9
  • 99
  • 140
  • You are misunderstanding what layout margins do. As the docs say, "Use this property so specify the desired amount of space (measured in points) between the edge of the view and any subviews". So the margins are between a view and its subviews, not for insetting the text in a label - the text is not a subview. – rdelmar Nov 12 '14 at 05:47

1 Answers1

2

If I were you, I would subclass UILabel and add UIEdgeInsets. In your subclass of UILabel do something like this:

.m file

    - (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;
    }
Robert J. Clegg
  • 7,231
  • 9
  • 47
  • 99
  • I tested this, and it doesn't quite work for all multi-line labels. Especially when you have a long word that gets moved to the next line because of the insets, the text can get truncated because the number of lines doesn't get calculated properly. – rdelmar Nov 12 '14 at 06:11
  • Ah yes, there is a small bug I noticed with multi-lines. There is a "bug" that makes it 1 point too short at times. I had this issue with multilines. I have updated my answer with an if statement in the intrinsicContentSize method. Try that out. Also set your label to word wrap and not character wrap. – Robert J. Clegg Nov 12 '14 at 06:27
  • I tried that, and it still didn't work with the OP's example -- the long text still got truncated (even with +=20 for the height). The accepted answer in the link I used to close the question works perfectly. – rdelmar Nov 12 '14 at 07:16
  • Thanks @rdelmar - I searched a bunch on SO but didn't find that post/answer. Worked perfectly! – runmad Nov 12 '14 at 15:09