-1

How do I add padding to a UILabel while positioning and sizing it with Auto Layout?

I tried subclassing it and overriding the drawTextInRect: method like this:

- (void)drawTextInRect:(CGRect)rect {

    CGFloat borderWidth = 5;

    CGFloat doubleBigSquareRadius = CGRectGetWidth(rect);
    CGFloat doubleSmallSquareRadius = doubleBigSquareRadius - borderWidth * 2;

    CGFloat smallSquareSideSize = doubleSmallSquareRadius / sqrt(2);
    CGFloat smallSquareOffset = (doubleBigSquareRadius - smallSquareSideSize) / 2;

    CGSize smallSquareSize = CGSizeMake(smallSquareSideSize, smallSquareSideSize);
    CGPoint smallSquareOrigin = CGPointMake(smallSquareOffset, smallSquareOffset);

    CGRect smallSquareFrame = CGRectMake(smallSquareOrigin.x, smallSquareOrigin.y, smallSquareSize.width, smallSquareSize.height);

    [super drawTextInRect:smallSquareFrame];
}

but it doesn't get called at all.

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113

2 Answers2

0

but it doesn't get called at all.

Perhaps because your label is not an instance of your subclass?

Here, start with this simple sample:

- (void)drawTextInRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextStrokeRect(context, CGRectInset(self.bounds, 1.0, 1.0));
    [super drawTextInRect:CGRectInset(rect, 5.0, 5.0)];
}

You need a UILabel subclass. Implement that in your subclass. Then make sure that your UILabel is an actual instance of that subclass. (If you're creating the label in the nib, it won't be by default.)

(Also note that autolayout won't magically know that this label behaves any differently from a normal label, so you might also have to override intrinsicContentSize, depending on your use case, in order to get the label to size itself in the way you desire.)

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • I'm actually trying to modify [this library](https://github.com/kirualex/KAProgressLabel), so I'm 100% it's a `KAProgressLabel` instance and not a simple `UILabel` instance, as it wouldn't show the colored progress. – Iulian Onofrei Sep 01 '17 at 08:23
  • Then you're not giving enough info, since I assure you that what said works. Do you need to see a working example in a downloadable project? – matt Sep 01 '17 at 13:49
  • I'll try to create a simple demo and try to reproduce it. – Iulian Onofrei Sep 01 '17 at 18:02
  • I figured out the problem while creating a demo project. Thank you for your interest. – Iulian Onofrei Sep 21 '17 at 08:45
0

My drawTextInRect: method was caused by the fact that KAProgressLabel was directly calling the super method here.

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113