iOS:如何对齐诸如whatsapp聊天消息标签和时间标签之类的标签?

时间:2018-08-09 11:12:32

标签: ios swift uilabel chat

在whatsapp中,如果消息很短,则文本和时间在同一行中。 如果消息很长,则时间在右下角-上方的文字。

如何在Ios中使用Storyboard实现此目的

enter image description here

2 个答案:

答案 0 :(得分:4)

尝试使用类似这样的方法来定义最后的行宽(也许您需要根据情况对文本容器进行更多调整):

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
}

然后,您可以确定日期标签的最后一行是否有足够的地方

用法示例:

// 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)

答案 1 :(得分:-1)

将Swift转换为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);
}