如何使用uitextview动态更改uitableviewcell的高度而不使用代码自动布局?我会在里面找到uitableviewcell和uitextview。 uitableviewcell将根据uitextview中的文本进行更改。
答案 0 :(得分:0)
这是我使用的代码(基于旧答案),评论描述每个部分:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//width can be customized based on your needs - i have a border of 10 around my textView on the sides
let width = tableView.frame.size.width - 20
if let textView = /* your cell's textView if initialized and presented*/ {
//if textView is available, use `sizeThatFits` to optimize size
let height = textView.sizeThatFits(CGSize(width:width, height: CGFloat.max)).height
return height //in my code I have a minimum threshold enforces via return ( height > 65.0) ? height : 65.0
}else{
//if it doesn't exist, use `textViewHeightForText` to simulate as if it did
return textViewHeightForText(/*text to display */, andWidth: width)
}
}
internal func textViewHeightForText(text: String?, andWidth width: CGFloat) -> CGFloat {
//in case you need to know height before cell has been presented (and textView not set up yet), can make one here
let calculationView = UITextView()
//IMPORTANT - have to specify the name/size of your font
let attributedText = NSAttributedString(string: (text != nil) ? text! : "", attributes: [NSFontAttributeName : UIFont(name: "Helvetica Neue", size: 16.0)!])
calculationView.attributedText = attributedText
let height = calculationView.sizeThatFits(CGSize(width: width, height: CGFloat.max)).height
return height
}
未显示,因为它取决于您的型号,是:
[NSIndexPath : UITextView]
,在cellForRowAtIndexPath
期间设置它并在if let
部分中访问它)< / LI>
textView
,则访问您的模型以获取将要显示的文本。这是必要的,因为它需要在显示单元格之前进行计划。答案 1 :(得分:0)
以编程方式使用它。你需要帮助autoResizingMask。您需要为UItableViewCell的所有4个边定义autoResizingMask到textview,然后需要检查您的文本。您需要为textview设置SizeToFit属性。他们是一种方法&#34; sizeWithFont constrainedToSize:lineBreakMode&#34;对于可以返回CGSize的NSString,你需要通过方法heightForRowAtIndexpath将高度从这个大小传递给UITableviewCell。这将解决您的问题。