NSMutableAttributedString add different alignments

Shmidt picture Shmidt · May 24, 2013 · Viewed 17.4k times · Source

Is it possible to add left and right alignments to different parts of the string?

I tried to add alignment attribute to the right part:

    NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
    [paragrahStyle setAlignment:NSTextAlignmentRight];
    [mutableAttributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:rangeOfDate];

But the whole string is aligned to the left.

Answer

jayjunck picture jayjunck · Sep 20, 2013

What you do in your code is to set the paragraph style (the text from \n to \n) and it is not possible to have multiple text alignments in the same paragraph. I had the same problem and ended up using multiple UILabels in iOS 6 :-(

However, in iOS 7 I noticed TabStops for ParagraphStyle. This actually makes it possible, but I find the documentation quite inadequate. However, I ended up getting it to work. You can set a right aligned TapStop, which causes your text to get rendered to the left of your specified stop (until that space is filled). In order to get my simple example to work I had to add at least one more attribute besides the paragraph one - it could have been just a clear UIColor for the background though :-)

The following is a simple example of drawRect in a UIView:

- (void)drawRect:(CGRect)rect
{
    NSString *str = @"to the left\tto the right\nleft again\tright again";
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:str];

    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.maximumLineHeight = 12.0f;
    paragraph.alignment = NSTextAlignmentLeft;

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

    [att addAttribute:NSBackgroundColorAttributeName value:[UIColor magentaColor] range:NSMakeRange(0, @"to the left".length)];
    [att addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Trebuchet-BoldItalic" size:12.0] range:NSMakeRange(12, 5)];
    [att addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(str.length - 4, 2)];
    [att addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, str.length)];

    [att drawInRect:rect];
}

That code will render the following:

enter image description here