iOS:如何对齐诸如whatsapp聊天消息标签和时间标签之类的标签? [英] Ios : How to align labels like whatsapp chat message label and time label?
本文介绍了iOS:如何对齐诸如whatsapp聊天消息标签和时间标签之类的标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在whatsapp中,如果消息很短,则文本和时间在同一行中。
如果消息很长,则时间在右下角-文本正上方。
In whatsapp, if the message is very short, the text and time are in the same row. If the message is long, the time is in the bottom right corner - the text coming above it.
如何在Ios中使用Storyboard实现此目标
How can i achieve this using Storyboard in Ios
推荐答案
尝试使用类似这样的方法来定义最后的行宽(也许您将不得不对文本容器进行一些调整):
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
用法示例:
// 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:如何对齐诸如whatsapp聊天消息标签和时间标签之类的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文