2

I've a label in a table cell and I wish to add padding to top,bottom,left and right.

CGRect initialFrame = CGRectMake(10,10,100,20);
UIEdgeInsets contentInsets = UIEdgeInsetsMake(5, 0, 5, 0);
CGRect padd = UIEdgeInsetsInsetRect(initialFrame, contentInsets);
self.rewardLabel = [[UILabel alloc] initWithFrame:padd];
self.rewardLabel.backgroundColor =[UIColor colorWithRed:0.192 green:0.373 blue:0.561 alpha:1];
self.rewardLabel.layer.cornerRadius = 5.0f;
self.rewardLabel.layer.masksToBounds = YES;
self.rewardLabel.textColor = [UIColor whiteColor];
self.rewardLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.rewardLabel.numberOfLines = 1;
self.rewardLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:14];
[self.contentView addSubview:self.rewardLabel];    

But it seem like not working. Can anyone tell me how to do?

pkamb
  • 33,281
  • 23
  • 160
  • 191
Vincia Tanqling
  • 57
  • 1
  • 11

1 Answers1

4

There are several ways on how to achieve this:

  1. If you do not need a specific background color for your label you could just adjust the labels frame to add the padding (e.g. if your text should start 20px from the cell's left side, set the label's frame's x to 20).
  2. To really add a padding, you could use a custom UILabel subclass and override its drawTextInRect: and intrinsicContentSize methods. (See this question for details)
  3. If you just need a left and right padding you could use an NSAttributedString to add insets to UILabel:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.headIndent = 5.0;
paragraphStyle.firstLineHeadIndent = 5.0;
paragraphStyle.tailIndent = -5.0;
NSDictionary *attrsDictionary = @{NSParagraphStyleAttributeName: paragraphStyle};
label.attributedText = [[NSAttributedString alloc] initWithString:@"Your text" attributes:attrsDictionary];
Community
  • 1
  • 1
joern
  • 27,354
  • 7
  • 90
  • 105