iosswiftuitableviewcelluitableviewautomaticdimension

Autoresizing UITableViewCell with UITextView which has text aligned to vertical center simultaneously?


Cell contains multiline text so I decided to use text view.

textView.textContainerInset = UIEdgeInsets.zero removes extra padding. Code to center it vertically:

extension UITextView {
    func centerVertically() {
        var topCorrect = (self.bounds.size.height - self.contentSize.height * self.zoomScale) / 2
        topCorrect = topCorrect < 0.0 ? 0.0 : topCorrect;
        self.contentInset.top = topCorrect
    }
}

This works if I predefine cell height in tableView(_:, heightForRowAt:).

But if I use UITableView.automaticDimension to resize the cell everything becomes broken.

How to solve this issue?


Solution

    1. Use auto layout and pin leading, trailing, top and bottom, constraints of textview to the cell.
    2. Disable scrolling in textview
    3. Add a height constraint such that height is greater than or equal to a constant value (this is a min value that will show on the screen) for textview
    4. User .automatic dimension

    Try this and let me know if this worked out for you