首页 > 解决方案 > Ios:如何对齐诸如whatsapp聊天消息标签和时间标签之类的标签?

问题描述

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

我如何在 iOS 中使用 Storyboard 来实现这一点

在此处输入图像描述

标签: iosswiftuilabelchat

解决方案


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

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)

推荐阅读