Ios : How to align labels like whatsapp chat message label and time label?

送分小仙女□ 提交于 2019-12-05 18:52:54

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!