Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel textRectForBounds has no effect when trying to create margin [duplicate]

I'm trying to indent the text in a UILabel to leave some margin around the text showing the background colour. Following the suggestion here I've overriden textRectForBounds:limitedToNumberOfLines: like so:

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
    CGRect intermediate = CGRectMake(bounds.origin.x+MARGIN,bounds.origin.y+MARGIN,bounds.size.width-2*MARGIN,bounds.size.height-2*MARGIN);
    return [super textRectForBounds:intermediate limitedToNumberOfLines:numberOfLines];
}

But no matter what I do, the text ends up tight against the left border of the rectangle. It seems as though the drawing is ignoring the origin part of the returned CGRect (although it seems to be respecting the width part, as if I reduce to width of intermediate to eg bounds.size.width-200 the rect that textRectForBounds returns is suitably narrow and the text is drawn in a long skinny column).

So: what else I need to do to the UILabel to make the drawing respect the textForRectBounds-returned-rect's origin.x and origin.y? I'd rather not override UILabel's drawTextInRect if I can help it.

Update: This was a long time ago and I can't remember exactly why the other question didn't work for me. I believe it was because I was trying to have a UILabel with multiple lines, and the solution here didn't work in that case.

like image 750
damian Avatar asked Feb 05 '11 13:02

damian


1 Answers

I think you should override both textRectForBounds:limitedToNumberOfLines: and drawTextInRect: like this:

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
    return CGRectInset(bounds, MARGIN, MARGIN);
}

- (void)drawTextInRect:(CGRect)rect
{
    [super drawTextInRect: CGRectInset(self.bounds, MARGIN, MARGIN)];
}
like image 111
Costique Avatar answered Nov 18 '22 03:11

Costique