Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
458 views
Welcome To Ask or Share your Answers For Others

1 Answer

What you do in your code is to set the paragraph style (the text from to ) 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 leftto the right
left againright 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...