簡體   English   中英

如何在段落中對齊UILabel文本

[英]How to align UILabel text in paragraph

根據客戶要求,我在設置文本對齊方面存在一個小問題。 客戶希望文本以段落方式與單獨行中的數字對齊。 請看下面的圖像,數字有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];

一種可能性:

  • 將NSAttributedString與自定義NSParagraphStyle一起使用。 第一行縮進可以與其他行(左邊距)不同。

另一種可能性

  • 使用Web視圖。 您所描述的內容很容易使用CSS進行配置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM