UILabel text margin

来源:互联网 发布:h5 翻牌抽奖源码 编辑:程序博客网 时间:2024/06/06 18:08

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 subclassing UILabel and overriding drawTextInRect: 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 of tc.'s answer. It has two advantages over that one:

  1. there's no need to trigger it by sending a sizeToFit message
  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 both textRectForBounds: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)];}