I am attempting to use NSMutableAttributedString to format text to be left aligned and right aligned on the same piece of text
I've reviewed a similar answer at IOS Multiple right and left align on same line but could not get the tab stops to work correctly.
My own solution is to do the following.
Have my copy + add physical tabs (ie: \t
) to the end of the copy
Then create a paragraph style for my chat time string which is right aligned and append this to the end of the string.
I've almost got it to work;
But the problem is the time isn't right aligned at all; it seems to be stuck left aligned.
I'd like the time text to be on the right hand side.
Here is my code for setting up the time part;
NSAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:message.body attributes:attributes];
NSMutableAttributedString *finalizedCopy = [attributedString mutableCopy];
if (message.sender.remoteID) [finalizedCopy appendAttributedString:tabStops];
// Add time to the chat bubble
NSString *messageTime = [[JSQMessagesTimestampFormatter sharedFormatter] timeForDate:message.date];
NSAttributedString *chatMessageTime = [[NSAttributedString alloc] initWithString:messageTime attributes:attributes];
NSMutableParagraphStyle *timeParagraphStyle = [[NSMutableParagraphStyle alloc] init];
timeParagraphStyle.alignment = NSTextAlignmentRight;
NSMutableAttributedString *dateString = [[NSMutableAttributedString alloc] initWithAttributedString:chatMessageTime];
[dateString setAttributes:@{ NSFontAttributeName : [UIFont vic_fontOfSize:10],
NSForegroundColorAttributeName: [UIColor vic_darkTextColor]
}
range:NSMakeRange(0, dateString.length)];
[dateString addAttribute:NSParagraphStyleAttributeName value:timeParagraphStyle range:NSMakeRange(0, dateString.length)];
[finalizedCopy appendAttributedString:dateString];
attributedString = [finalizedCopy copy];
I am wondering how to best achieve the desired effect.
Many thanks
Also, if I were to use NSTabStops -- where do I put them, at the end of my left-hand string or at the start of my right-hand string?
ie:
NSTextTab *tabStop = [[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentRight location:150 options:nil];
[paragraph setTabStops:@[tabStop]];
[finalizedCopy addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, finalizedCopy.length)];
Is at the end of my left-hand string but I see no results visually.