Update code in Swift 4.2
Courtesy: http://www.swiftdevcenter.com/the-dynamic-height-of-uitextview-inside-uitableviewcell-swift/.
Create a custom cell called GrowingCell, add a UITextView to the cell and create an Outlet of this. Register this cell in a 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 go to the Custom GrowingCell cell and add the following 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()
For more details: visit this full demo
source share