我最近开始在 Xcode 中使用 Swift 开发一个应用程序,并尝试创建一个文本气泡。为此,我需要获取多行 UILabel 中最长文本行的宽度。例如,如果我有这段文字(我会在一定长度后自动设置换行符):
Hello there, this is
an example piece of text
我想返回第二行文本的宽度。我已经尝试使用 sizeToFit() 来大大简化我的工作,但是由于我的其他代码,这不是一个选项,因为它会导致其他问题(我的代码在下面)。是否有一种不使用 sizeToFit() 的纯编程方式来获取此值?任何帮助将非常感激。我的代码:
bubbleContents.text = textMessage
bubbleContents.numberOfLines = 0
bubbleContents.lineBreakMode = .byWordWrapping
bubbleContents.bounds.size.width = 2000
var widthText = bubbleContents.intrinsicContentSize.width
bubbleContents.bounds.size.width = 266
print(textMessage)
print(widthText)
if widthText > 266 {
let numRows = Int(widthText/266)
print(numRows)
//bubbleContents.frame.origin.y += CGFloat((Double(numRows)*10.25))
var currentHeight = 44.0
currentHeight += Double((Double(numRows)*20.5))
bubbleContents.bounds.size.height = CGFloat(currentHeight)
heightOfCell = Double(currentHeight)
let originalTransform = self.bubbleContents.transform
let scaledTransform = originalTransform
let scaledAndTranslatedTransform = scaledTransform.translatedBy(x: 0, y: CGFloat(Double(numRows)*20.5))
//self.bubbleContents.transform = scaledAndTranslatedTransform
}
else {
heightOfCell = 44.0
}
bubble.frame = CGRect(x: 0, y: 0, width: Double(widthText + 30), height: heightOfCell - 4)
bubbleContents.center.y = bubble.center.y
这是我当前文本气泡的图像:
最佳答案
您可以使用 NSAttributedString,boundingRect(with:options:context:)
方法,首先创建 NSAttributedString
具有诸如 UILabel
字体等属性
let attributes: [NSAttributedString.Key : Any] = [.font: bubbleContents.font]
let atStr = NSAttributedString(string: textMessage, attributes: attributes)
现在使用 atStr.boundingRect(with:options:context:)
方法,像这样:
let bounds = CGSize(width: 266.0, height: .greatestFiniteMagnitude)
let bubbleSize = atStr.boundingRect(with: bounds, options: [.usesLineFragmentOrigin, .usesFontLeading, .usesDeviceMetrics], context: nil).size
用法:
bubble.frame.size.width = bubbleSize.width
bubble.frame.size.height = max(bubbleSize.height, 44.0)
关于ios - 如何根据 UILabel 行宽设置 UIImageView 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55669685/