Hello everyone, this article I write about how dynamic UITextView inside UITableViewCell.
First, I created the viewcontroller to create only one normal table view, the height setting of the cell is UITableViewAutomaticDimension to help UITableViewCell automatically scale according to the content inside:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.register(UINib(nibName: "AddCell", bundle: nil), forCellReuseIdentifier: "AddCell") tableView.estimatedRowHeight = 155 tableView.rowHeight = UITableView.automaticDimension } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "AddCell", for: indexPath) as? AddCell else { return UITableViewCell() } cell.delegate = self return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } } |
Next, I will create a cell named “AddCell”, after creating, I drag a UITextView inside and auto layout like this:
Inside the AddCell.swift file, I implement UITextViewDelegate and create AddCellDelegate as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import UIKit protocol AddCellDelegate: class { func addText() } class AddCell: UITableViewCell { @IBOutlet weak var textView: UITextView! weak var delegate: AddCellDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) textView.delegate = self } } extension AddCell: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { self.delegate?.addText() } } |
Finally, in the ViewController file, I implement AddCellDelegate:
1 2 3 4 5 6 7 | extension ViewController: AddCellDelegate { func addText() { tableView.beginUpdates() tableView.endUpdates() } } |
I set the color of the table view is gray, the text view is while to see more clearly, the results I get are as follows:
Thank you for reading my article