In whatsapp, if the message is very short, the text and time are in the same row. If the message is long, the time is in the bottom right corner - the text coming above it.
How can i achieve this using Storyboard in Ios
Try using something like this to define last line width (Maybe you'll have to tweak text container a bit more for your case):
public func lastLineMaxX(message: NSAttributedString, labelWidth: CGFloat) -> CGFloat {
// Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
let labelSize = CGSize(width: bubbleWidth, height: .infinity)
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: labelSize)
let textStorage = NSTextStorage(attributedString: message)
// Configure layoutManager and textStorage
layoutManager.addTextContainer(textContainer)
textStorage.addLayoutManager(layoutManager)
// Configure textContainer
textContainer.lineFragmentPadding = 0.0
textContainer.lineBreakMode = .byWordWrapping
textContainer.maximumNumberOfLines = 0
let lastGlyphIndex = layoutManager.glyphIndexForCharacter(at: message.length - 1)
let lastLineFragmentRect = layoutManager.lineFragmentUsedRect(forGlyphAt: lastGlyphIndex,
effectiveRange: nil)
return lastLineFragmentRect.maxX
}
Then you can decide if there is enough place for your date label in the last line or not
usage example:
// you definitely have to set at least the font to calculate the result
// maybe for your case you will also have to set other attributes
let attributedText = NSAttributedString(string: self.label.text,
attributes: [.font: self.label.font])
let lastLineMaxX = lastLineMaxX(message: attributedText,
labelWidth: self.label.bounds.width)
Convert Swift to Objective-C
- (void)lastlineWidth {
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:self.label.font forKey:NSFontAttributeName];
NSAttributedString *message = [[NSAttributedString alloc] initWithString:self.label.text attributes:attrsDictionary];
CGSize labelSize = CGSizeMake(self.label.bounds.size.width, INFINITY);
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:labelSize];
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:message];
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
textContainer.lineFragmentPadding = 0.0;
textContainer.lineBreakMode = NSLineBreakByWordWrapping;
textContainer.maximumNumberOfLines = 0;
NSInteger lastGlyphIndex = [layoutManager glyphIndexForCharacterAtIndex:message.length-1];
CGRect lastLineRect = [layoutManager lineFragmentUsedRectForGlyphAtIndex:lastGlyphIndex effectiveRange:nil];
NSLog(@"lastLineWidth = %f", lastLineRect.size.width);
}
来源:https://stackoverflow.com/questions/51765460/ios-how-to-align-labels-like-whatsapp-chat-message-label-and-time-label