Update code in Swift 4.2
Credit: http://www.swiftdevcenter.com/the-dynamic-height-of-uitextview-inside-uitableviewcell-swift/
Create a Custom cell with name GrowingCell, add UITextView in the cell and create an Outlet of this. Register this cell in UITableView in your ViewController class.
Your ViewController:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let nib = UINib(nibName: "GrowingCell", bundle: nil)
self.tableView.register(nib, forCellReuseIdentifier: "GrowingCell")
self.tableView.tableFooterView = UIView()
self.tableView.dataSource = self
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GrowingCell", for: indexPath) as! GrowingCell
cell.cellDelegate = self
return cell
}
}
extension ViewController: GrowingCellProtocol {
// Update height of UITextView based on string height
func updateHeightOfRow(_ cell: GrowingCell, _ textView: UITextView) {
let size = textView.bounds.size
let newSize = tableView.sizeThatFits(CGSize(width: size.width,
height: CGFloat.greatestFiniteMagnitude))
if size.height != newSize.height {
UIView.setAnimationsEnabled(false)
tableView?.beginUpdates()
tableView?.endUpdates()
UIView.setAnimationsEnabled(true)
// Scoll up your textview if required
if let thisIndexPath = tableView.indexPath(for: cell) {
tableView.scrollToRow(at: thisIndexPath, at: .bottom, animated: false)
}
}
}
}
Now move to your Custom GrowingCell cell and add below code:
import UIKit
protocol GrowingCellProtocol: class {
func updateHeightOfRow(_ cell: GrowingCell, _ textView: UITextView)
}
class GrowingCell: UITableViewCell {
weak var cellDelegate: GrowingCellProtocol?
@IBOutlet weak var textView: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
textView.delegate = self
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension GrowingCell: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
if let deletate = cellDelegate {
deletate.updateHeightOfRow(self, textView)
}
}
}
For more detail: visit this full demo