iosswiftuitableviewtextviewuitableviewautomaticdimension

Make tableview cell expand with textView text size


For this i studied many tutorial But I was not able to find solution for my problem

I want to show textView's on table cell. and Cell should expand with the text entered by user in the textView.

As I found there are two ways to do this

first one:-

self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 30;


func textViewDidChange(_ textView: UITextView!, for indexPath: IndexPath!) {
    self.presenter?.valueChanged(section: indexPath.section, value: textView.text)
    isChanged = true

    self.tableView.beginUpdates()
    self.tableView.endUpdates()
}
Make the table view to adjust height automatically. But in this case when there is no data to display in cellForRow at index path then textview height is automatically adjusted to 0 and i was not able to select the text view.

Second way :-

remove the automatic dimension code

// MARK: TextViewTableViewCellDelegate
func textViewDidChange(_ textView: UITextView!, for indexPath: IndexPath!) {
    self.presenter?.valueChanged(section: indexPath.section, value: textView.text)
    isChanged = true

    self.tableView.beginUpdates()
    self.tableView.endUpdates()
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    var ret = DEFAULT_CELL_HEIGHT

    if let cell = tableView.dequeueReusableCell(withIdentifier: SECTION_TYPE_FREEFORM) as? TextViewTableViewCell {
        cell.textView.text = self.presenter?.cellBody(section: indexPath.section)
        cell.textView.sizeToFit()

        let width = self.view.frame.size.width - HORIZONTAL_PADDING
        let calculatedHeight = cell.textView.sizeThatFits(CGSize(width: width, height: CGFloat(MAXFLOAT))).height + 10
        if(calculatedHeight > ret) {
            ret = calculatedHeight
        }
    }

    return ret
}

But in this I checked that then I create cell in the heightForRowAtIndexPath method then textview height is not appropriate. And it is not exactly working to adjust the height automatically.

Kindly suggest the solution for the same. Thanks in Advance.


Solution

  • What about adding a minimum height constraint to your textview and using the first method? Just make sure the scrolling of your UITextView is disabled. Because the only issue you have on the first solution is the cell height being too small when nothing is in there...

    Otherwise you code seems pretty good and might give you smooth animation.