Ios:如何对齐whatsapp聊天消息标签和时间标签等标签?

2024-01-22

在 Whatsapp 中,如果消息很短,则文本和时间位于同一行。 如果消息很长,时间位于右下角 - 文本位于其上方。

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


尝试使用类似的东西来定义最后一行的宽度(也许您需要根据您的情况稍微调整文本容器):

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ios:如何对齐whatsapp聊天消息标签和时间标签等标签? 的相关文章

随机推荐