0

My goal is to have the first line with a centered text and the second line where it is, right-aligned.

Is this possible?

I used attributed strings passing NSParagraphStyleAttributeName with the desired alignment but the UILabel seems to consider only the last paragraph style.

NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];

// Mathemagika
paragraph.alignment = NSTextAlignmentCenter;
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]
                                      initWithString:fullStr];
[attrStr addAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"Noteworthy-Bold" size:30.f],
                         NSParagraphStyleAttributeName : paragraph}
                 range:NSMakeRange(0, fullStr.length)];

// ©
paragraph.alignment = NSTextAlignmentCenter;
NSAttributedString *attrStr2 = [[NSAttributedString alloc]
                                initWithString:@"©"
                                attributes:@{NSBaselineOffsetAttributeName : @20,
                                             NSFontAttributeName : [UIFont fontWithName:@"Noteworthy-Bold" size:10.f],
                                             NSParagraphStyleAttributeName : paragraph}];
[attrStr appendAttributedString:attrStr2];

// Interactive Math Formulae
paragraph.alignment = NSTextAlignmentRight;
NSAttributedString *attrStr3 = [[NSAttributedString alloc]
                                initWithString:@"\nInteractive Math Formulae\n"
                                attributes:@{NSFontAttributeName : [UIFont fontWithName:@"Noteworthy-Bold" size:10.f],
                                             NSParagraphStyleAttributeName : paragraph}];
[attrStr appendAttributedString:attrStr3];

UILabel *titleLabel = [UILabel new];
[titleLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[titleLabel setAttributedText:attrStr];
titleLabel.backgroundColor = self.view.backgroundColor;
[view addSubview:titleLabel];
Community
  • 1
  • 1
Lucien
  • 8,263
  • 4
  • 30
  • 30
  • looks similar [to this](http://stackoverflow.com/questions/16737503/nsmutableattributedstring-add-different-alignments) – Dima Mar 21 '14 at 20:38

1 Answers1

1

I took a quick look and found this link:

NSMutableAttributedString add different alignments

Applying the use of tabs to your application, I came up with this:

NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
paragraph.alignment = NSTextAlignmentCenter;

NSTextTab *t = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentRight location:labelFrame.size.width options:nil];
paragraph.tabStops = @[t];

And then defined the same paragraph style throughout rather than trying to change it from center to right aligned. (I added the green box to make it obvious where my borders are.)

enter image description here

Community
  • 1
  • 1
smallwisdom
  • 191
  • 6