ios - Ios:如何对齐诸如whatsapp聊天消息标签和时间标签之类的标签?
解决方案
尝试使用类似这样的东西来定义最后一行的宽度(也许你需要根据你的情况对文本容器进行更多的调整):
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)
推荐阅读
- python - 如何打包我的 Python 烧瓶项目,使客户看不到代码以及当客户启动他的 windows 10 专业版时
- python - 如何从不一致的字符串列表中获取子字符串?
- arrays - 我想使用 Substring 函数并追加
- javascript - JavaScript while 与性能对比
- amazon-web-services - 如何将功能自动部署到 AWS Azure 和 GCP
- java - 我想通过 log4j 记录 STORM 日志并将日志发送到 kafka。结果是kafka STORM可以自己记录日志log4j但不能将日志发送到kafka
- python - 使用python进行DTMF解码
- r - How to convert 3 hourly data into hourly data?
- php - 带有附件的邮件没有通过邮件到达?
- javascript - 从最后一个点(。)之前替换字符串