views:

68

answers:

2

Hi everyone. I think I'm missing something really simple here but I'm looking to set the left inset/margin of a UILabel and can't seem to see a method to do so. The label has a background set so it would be ideal to inset the text by 10px or so on the left hand side. Any help would be appreciated.

Thanks, Laurence

A: 

I think UILabel class have no method for setting margin. Why you not set the position of Label at required place ?

See below code

UILabel *label = [[UILabel alloc] init];
label.text = @"This is label";
label.frame = CGRectMake(0,0,100,100);

if from interface builder then just position Label by following
yourLabel.frame = CGRectMake(0,0,100,100);

Hiren Gujarati
A: 

If you don't want to use an extra parent view to set the background, you can subclass UILabel and override textRectForBounds:limitedToNumberOfLines:. I'd add a textEdgeInsets property or similar and then do

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
  return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds,textEdgeInsets) limitedToNumberOfLines:numberOfLines];
}

For robustness, you might also want to call [self setNeedsDisplay] in setTextEdgeInsets:, but I usually don't bother.

tc.