我可以实时更改UITableViewCell的高度吗? [英] Can I change height of UITableViewCell real-time?
本文介绍了我可以实时更改UITableViewCell的高度吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有UITableViewCell
,而在该单元格内部,我有UITextView
.当我要更改UITextView
的文本时,我想实时更改单元格 height 吗?
I have UITableViewCell
and inside of that cell I have a UITextView
. When I will change text of UITextView
I want to change cell height real time?
我该怎么做?谢谢.
推荐答案
此解决方案的主要思想是计算textView的高度并将其分配给它的行.
The main idea of this solution is to calculate the textView's height and assigns it to its row.
注意:这是Swift 3代码:
Note: this is Swift 3 code:
class ViewController: UIViewController {
// array containing rows heights:
var rowHeights = [CGFloat]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// fill it with default values of row heights
for _ in 1...10 {
rowHeights.append(44)
}
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return rowHeights[indexPath.row]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return the actual number of your rows...
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TextViewTableViewCell") as! TextViewTableViewCell
// assgin the tag of current text view to use for determining the current cell's height
cell.textView.tag = indexPath.row
cell.textView.delegate = self
return cell
}
}
extension ViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
// calculate the current height and append it in the rowHeights depends on the textView's tag. Add your the textView fontSize instead of 15
rowHeights[textView.tag] = (textView.text?.heightWithConstrainedWidth(width: tableView.frame.size.width, font: UIFont.systemFont(ofSize: 15)))!
// for updating the tableView appearence (don't use "reloadData", it will resignFirstResponder the textView)
tableView.beginUpdates()
tableView.endUpdates()
textView.setContentOffset(CGPoint.zero, animated: true)
//textView.becomeFirstResponder()
}
}
extension String {
// this method calculates the height of string depending on your view width and font
func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return boundingBox.height
}
}
CustomTableViewCell:
CustomTableViewCell:
class TextViewTableViewCell: UITableViewCell {
@IBOutlet weak var textView: UITextView!
}
输出应如下所示:
希望有帮助.
这篇关于我可以实时更改UITableViewCell的高度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文