Search code examples
iostext-alignmentnsmutableattributedstring

Multiple text alignment with same label using NSMutableAttributedString on iOS


I want to set Text direction for my label using NSMutableAttributedString. for example, I have chat view, which contains message and time. I want to set left alignment for message and right alignment for time using UILabel.

I have used following code, but it's not working,

 NSString *Time = [Functions stringFromGivenDate:msg.time withFormate:@"hh:mm a"];
 NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",msg.text,Time]];
 NSDictionary *attrDictionary = @{NSWritingDirectionAttributeName:@[@(NSTextWritingDirectionOverride)]};

[str addAttributes:attrDictionary range:NSMakeRange(msg.text.length+1, Time.length)];

Solution

  • if I understood correctly, this should help:

     NSMutableParagraphStyle *style  = [[NSMutableParagraphStyle alloc] init];
            style.alignment = alignment;// type NSTextAlignment
            NSDictionary *attributtes = @{NSParagraphStyleAttributeName : style,};