到目前为止,我一直在使用此方法估计集合视图中文本的高度和宽度,以设置聊天气泡的单元格高度,宽度和高度。
func estimateFrameForText(text: String) -> CGRect {
let size = CGSize(width: 230, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(NSStringDrawingOptions.usesLineFragmentOrigin)
let attributes = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 16)]
let frame = NSString(string: text).boundingRect(with: size, options: options, attributes: attributes, context: nil)
return frame
}
但是我从后端获得的文本有html编码的字符串。所以单引号变成'等等。如何估计实际字符的文本框架而不是html编码的字符串?
答案 0 :(得分:1)
首先解码html编码的字符串,然后计算字符串的高度
extension String {
init?(htmlEncodedString: String) {
guard let data = htmlEncodedString.data(using: .utf8) else {
return nil
}
let options: [String: Any] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
]
guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {
return nil
}
self.init(attributedString.string)
}}
使用此扩展名
let decodedString = String(htmlEncodedString: encodedString)