使用NSMutableAttributedString为UILabel添加填充。

3
我希望为一个高亮的UILabel添加一些内边距(见截图)。 enter image description here 我已经尝试过子类化UILabel,但没有成功:
- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.edgeInsets = UIEdgeInsetsMake(5, 5, 0, 0); //customize padding here
    }
    return self;
}

- (void)drawTextInRect:(CGRect)rect {
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}

当前创建标签的功能:

    paddingLabel  *viewTitleLabel = [[paddingLabel alloc]initWithFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, view.frame.size.height)];

    NSMutableAttributedString *s =
    [[NSMutableAttributedString alloc] initWithString:ticketcode];

    [s addAttribute:NSBackgroundColorAttributeName
              value:[UIColor blackColor]
              range:NSMakeRange(0, s.length)];


    viewTitleLabel.attributedText = s;

给标签添加填充?你是指在图像前面需要一些空间吗? - undefined
更像是对所有四个边的插入物。 - undefined
1个回答

0
快速解决左缩进的方法:
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 10
paragraphStyle.headIndent = 10
let attributedString = NSMutableAttributedString(string: string, attributes: attributes)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接