2

我在表格单元格中有一个标签,我希望在顶部、底部、左侧和右侧添加填充。

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];    

但这似乎不起作用。谁能告诉我该怎么做?

4

1 回答 1

4

有几种方法可以实现这一点:

  1. 如果您的标签不需要特定的背景颜色,您只需调整标签框架以添加填充(例如,如果您的文本应从单元格左侧开始 20px,则将标签框架的 x 设置为 20)。
  2. 要真正添加填充,您可以使用自定义 UILabel 子类并覆盖其drawTextInRect:intrinsicContentSize方法。(有关详细信息,请参阅此问题
  3. 如果您只需要左右填充,则可以使用 NSAttributedString 向 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];

于 2015-05-15T15:00:37.180 回答