How to have 2 alignments in a UILabel

304 Views Asked by At

I am trying to create a UILabel where some of the text is aligned to the right and some of the text is aligned to the left. It is similar to the UITableViewCell with the small arrow:

enter image description here

I am trying to do it with NSAttributedString , but can't figure out what is the correct way to tackle this.

Here is some code which isn't working. It is aligned to the right.

NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:@"Label >"];

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

        [att addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, @"Label".length)];

        NSMutableParagraphStyle *rightParagraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.alignment = NSTextAlignmentRight;
        [att addAttribute:NSParagraphStyleAttributeName value:rightParagraph range:NSMakeRange(5, 1)];
3

There are 3 best solutions below

0
On

I did it before with that code, Hope it also working for you.

NSString* alphaString = @“some text”;

NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = NSTextAlignmentLeft;

NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] 
                                               initWithString:alphaString 
                                               attributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                               [UIFont fontWithName:@"HelveticaNeue" size:13],      NSFontAttributeName, 
    paragraphStyle, NSParagraphStyleAttributeName, nil]];

NSString * betaString = @“some other text”;

NSMutableParagraphStyle* paragraphStyle2 = [[NSMutableParagraphStyle alloc] init];
paragraphStyle2.alignment = NSTextAlignmentRight;


[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:betaString attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaNeue" size:13], NSFontAttributeName, paragraphStyle2, NSParagraphStyleAttributeName, nil]]];

yourLabel.attributedText = attributedString;
1
On

You can use NSAttributedString to achieve your requirements, but it will be much better and cleaner approach to use two UILabels instead.

0
On

Use 2 labels.Assign the needed TextAlignment property to them. And after setting label text value, write this line :

[textLabel sizeToFit];

Though sizes of the labels varies it will set to minimum size. and will avoid text overlap.