UILabel text margin

Q:

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.


A:

solved this by subclassingUILabeland overridingdrawTextInRect:like this:

- (void)drawTextInRect:(CGRect)rect { UIEdgeInsets insets = {0, 5, 0, 5}; return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)]; }

As you might have gathered, this is an adaptation oftc.'s answer. It has two advantages over that one:

  1. there's no need to trigger it by sending asizeToFitmessage
  2. it leaves the label frame alone - handy if your label has a background and you don't want that to shrink

A:

I think you should override bothtextRectForBounds:limitedToNumberOfLines:anddrawTextInRect: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)]; }

你可能感兴趣的:(UILabel)