如何在段落中对齐UILabel文本

时间:2016-03-10 05:20:24

标签: ios objective-c iphone uilabel

根据客户要求,我在设置文本对齐方面存在一个小问题。客户希望文本以段落方式与单独行中的数字对齐。请看下面的图像,数字有19像素填充和文本以段落方式对齐,41像素填充。

enter image description here

如果我们将左对齐设置为标签,我们将获得数字下方的第二行。

enter image description here

我尝试搜索解决方案,但无法成功。

提前致谢。

3 个答案:

答案 0 :(得分:4)

您需要为问题部分和答案部分设置不同的属性。您已经这样做来控制字体,所以它不应该是一个很大的变化。您需要为每个部分设置段落样式。对于问题部分,您需要将firstLineHeadIndent设置为19,将headIndent设置为41.对于答案部分,您需要将两者都设置为41。

NSMutableParagraphStyle *questionStyle = [[NSMutableParagraphStyle alloc] init];
questionStyle.firstLineHeadIndent = 19;
questionStyle.headIndent = 41;
NSDictionary *questionAttributes = @{
    NSParagraphStyleAttributeName: questionStyle,
    NSFontAttributeName: [UIFont systemFontOfSize: 20]
};

NSMutableParagraphStyle *answerStyle = [questionStyle mutableCopy];
answerStyle.firstLineHeadIndent = questionStyle.headIndent;
NSDictionary *answerAttributes = @{
    NSParagraphStyleAttributeName: answerStyle,
    NSFontAttributeName: [UIFont systemFontOfSize: 16]
};

NSMutableAttributedString *richText = [[NSMutableAttributedString alloc] init];
[richText appendAttributedString:[[NSAttributedString alloc]
     initWithString:questionText attributes:questionAttributes]];
[richText appendAttributedString:[[NSAttributedString alloc]
    initWithString:answerText attributes:answerAttributes]];

label.attributedText = richText;

答案 1 :(得分:1)

试试这个

NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.alignment = NSTextAlignmentLeft;
[self.titleString drawWithRect:CGRectMake(xOffset, yOffset, titleLabelSize.width, titleLabelSize.height)
                               options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine
                            attributes:@{ NSParagraphStyleAttributeName:paragraphStyle}
                               context:nil];

答案 2 :(得分:1)

一种可能性:

  • 将NSAttributedString与自定义NSParagraphStyle一起使用。第一行缩进可以与其他行(左边距)不同。

另一种可能性:

  • 使用网络视图。您所描述的内容很容易使用CSS进行配置。
相关问题