Raghavandra Santosh
Raghavandra Santosh

Reputation: 181

How to align UILabel text in paragraph

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.

enter image description here

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

enter image description here

I tried search for solution but not able to succeed.

Thanks in advance.

Upvotes: 4

Views: 1353

Answers (3)

rob mayoff
rob mayoff

Reputation: 385660

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;

Upvotes: 4

matt
matt

Reputation: 535232

One possibility:

  • Use an NSAttributedString with a custom NSParagraphStyle. The first line indent can be different from the other lines (left margin).

Another possibility:

  • Use a web view. What you describe is easy to configure using CSS.

Upvotes: 2

Awesome.Apple
Awesome.Apple

Reputation: 1324

Try this

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

Upvotes: 1

Related Questions