在UIlabel文本中添加填充?

时间:2015-05-15 11:11:24

标签: objective-c uilabel padding uiedgeinsets

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

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

但它似乎不起作用。任何人都可以告诉我该怎么办?

1 个答案:

答案 0 :(得分:4)

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

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