gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:55:06 38 4
gpt4 key购买 nike

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

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

enter image description here

最佳答案

尝试使用类似这样的方法来定义最后一行的宽度(也许您需要针对您的情况稍微调整文本容器):

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)

关于iOS : How to align labels like whatsapp chat message label and time label?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51765460/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com