如何在段落中对齐 UILabel 文本 [英] How to align UILabel text in paragraph

查看:24
本文介绍了如何在段落中对齐 UILabel 文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在根据客户要求设置文本对齐方式时遇到了一个小问题.客户希望文本以段落方式与单独行中的数字对齐.请参见下图,数字内边距为 19 像素,文本以段落方式对齐,内边距为 41 像素.

I have a small issue in setting text alignment as per client requirement. Client want text to be aligned in paragraph manner with numbers in separate line. Please see the below image the number have 19 pixels padding and text aligned in paragraph manner with 41 pixels padding.

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

If we set left alignment to label we will get the second line below the numeric.

我尝试寻找解决方案,但未能成功.

I tried search for solution but not able to succeed.

提前致谢.

推荐答案

您需要为问题部分和答案部分设置不同的属性.您已经在执行此操作来控制字体,因此应该不会有太大变化.您需要为每个部分设置段落样式.对于问题部分,您需要将 firstLineHeadIndent 设置为 19,将 headIndent 设置为 41.对于答案部分,您需要将两者都设置为 41.

You'll need to set different attributes for the question part and the answer part. You're already doing this to control the font, so it shouldn't be a big change. You need to set the paragraph style for each section. For the question section, you need to set the firstLineHeadIndent to 19 and the headIndent to 41. For the answer section, you need to set both to 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;

这篇关于如何在段落中对齐 UILabel 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆