The main idea of this solution is to calculate the textView's height and assigns it to its row.
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:
class TextViewTableViewCell: UITableViewCell {
@IBOutlet weak var textView: UITextView!
}
The output should looks like this:
Hope That Helped.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…