4

I'm trying to have a UITableView with several cells types. One of my cells needs to dynamically change his height while typing text in it. Here is the code for change the cell's height (in the cell's class), which works good:

func textViewDidChange(_ textView: UITextView)
{
    var newFrame:CGRect = noteTextView.frame
    newFrame.size.height = noteTextView.contentSize.height
    noteTextView.frame = newFrame
    self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.width, height: noteTextView.contentSize.height)
}

But the cell is overlaying the cell under him. Nor adding those lines on the parent tableView member helped:

mParentTableView.setNeedsLayout()
mParentTableView.layoutIfNeeded()

Any idea how to tell the tableView recalc its contained cells sizes ?

(XCode 9, Swift 4)

  • First, the cell is what you need to update, not the table. Second, are the cells subclassed? Third, you need to take full advantage of auto layout for this to work and I don't see any constraints in your code. – trndjc Feb 18 '18 at 16:59

2 Answers2

4

Using tableView's [tableView beginUpdates] and [tableView endUpdates] will solve this issue. See this answer for more information.

Matic
  • 393
  • 3
  • 12
3

Set delegate On Your UITableViewCell like that

var textDidChanges: (() -> Void)? = nil

func textViewDidChange(_ textView: UITextView) {
    textDidChanges?()
}

and Your tableView cellForRowAt

cell.textDidChanges = {
    self.tableView.beginUpdates()
    self.tableView.endUpdates()
} 

How to make a UITableViewCell with a UITextView inside, that dynamically adjust its height, on the basis of the UITextView?

AshvinGudaliya
  • 3,234
  • 19
  • 37