如何在段落中对齐UILabel文本

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

在这里输入图像描述

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

我试图寻找解决方案,但无法成功。

提前致谢。


您需要为问题部分和答案部分设置不同的属性。 你已经这样做来控制字体,所以它不应该是一个大的改变。 您需要为每个部分设置段落样式。 对于问题部分,您需要将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;

尝试这个

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

一种可能性:

  • 使用带有自定义NSParagraphStyle的NSAttributedString。 第一行缩进可以不同于其他行(左边距)。
  • 另一种可能:

  • 使用网络视图。 你所描述的很容易使用CSS进行配置。
  • 链接地址: http://www.djcxy.com/p/28267.html

    上一篇: How to align UILabel text in paragraph

    下一篇: Using SizeToFit() to Top Align UILabel Causes Jumping