我有一个UICollectionViewCell
,它有一个UITextView
作为其子视图,锚定到单元格的边界。计算UICollectionViewCell height base don UITextView属性文本
我在这里想要实现的是基于UITextView attributedString
,计算UITextView
应具有的高度,以便不滚动并将该大小应用于单元格的高度。
这里的问题是,NSAttributedString
可能有不同的字体大小,它也可能有一些图像,这将增加其大小。
如何根据可以具有多种内在形式(尺寸,换行符,图像)的内容计算尺寸?
我使用应用以下功能,但它不能在这种情况下工作,因为内部内容,如字体大小可能推迟,这不是常数:
private func estimatedHeightForText(_ text: String) -> CGFloat {
let approximateWidthOfBioTextView = view.frame.width - 24 // paddings
let size = CGSize(width: approximateWidthOfBioTextView, height: 1000) // height of 1000 is an arbitrary value
let attributes = [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 12)] // attributes of the text
// gets the estimation height based on Text
let estimatedFrame = NSString(string: text).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
return estimatedFrame.height
}
任何提示?
非常感谢。