我想动态计算tableView中textView
的高度,以便在heightForRowAt
中使用。我不要想要使用自动尺寸,因为它经常弄乱我在containerViews
中的滚动。
目前我正在为每个单元格实例化textView
,添加文本并使用高度获取高度:
var textViewForCellHeight = UITextView()
textViewForCellHeight.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
textViewForCellHeight.frame = CGRect(x: 0, y: 0, width: self.tableView.frame.size.width - cellHorizontalPadding - tableView.safeAreaInsets.left - tableView.safeAreaInsets.right, height: 0)
textViewForCellHeight.text = myString
textViewForCellHeight.sizeToFit()
return textViewForCellHeight.frame.size.height
在heightForRowAt
中使用它可以正常工作,并为单元格提供正确的高度,但它很昂贵并且显着减慢了tableView
。有没有更有效的方法来使用textView
动态获取tableView单元格的高度?
答案 0 :(得分:0)
试试这段代码:
<spring.version>4.0.0.RELEASE</spring.version>
答案 1 :(得分:0)
你可以简单地在这个函数中传递你的字符串,你将根据你的字符串获得动态高度。
func calculateHeight(inString:String) -> CGFloat
{
let messageString = input.text
let attributes : [NSAttributedStringKey : Any] = [NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : UIFont.systemFont(ofSize: 15.0)]
let attributedString : NSAttributedString = NSAttributedString(string: messageString!, attributes: attributes)
let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)
let requredSize:CGRect = rect
return requiredSize.height
}