如何对齐段落中的 UILabel 文本

How to align UILabel text in paragraph

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

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

我尝试搜索解决方案但未能成功。

提前致谢。

试试这个

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.
  • 配置

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