UILabel 文字靠右显示 并且 文字尾部距UILabel有一定的距离,使用attributeString

如题

使用UILabel时候想要文字靠右显示,但是不想顶着UILabel的尾部显示,类似于设置UIButton 的edge。 UILabel好像不可以直接设置edge,所以选择使用UILabel的attributedText。

以下是代码把想要的Label和想要表示的文字作为参数传入方法就可以了。

- (void)setAttributeStringForPriceLabel:(UILabel *)label text:(NSString *)text
{
    NSMutableAttributedString *attrString = [[NSMutableAttributedString
                                              alloc] initWithString:text];
    NSUInteger length = [text length];
    NSMutableParagraphStyle *
    style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    style.tailIndent = -10; //设置与尾部的距离
    style.alignment = NSTextAlignmentRight;//靠右显示
    [attrString addAttribute:NSParagraphStyleAttributeName value:style
                       range:NSMakeRange(0, length)];
    label.attributedText = attrString;
}

PS:同理设置左对齐的时候 还要为首行多设置一个属性:

    style.firstLineHeadIndent = 10;

通过对UILabel的Attribute的使用,多行显示的时候还可以设置相邻两行文字的间距等。 总之花式UILabel的时候不要忘了 attributeString !

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章