iosswiftuitableviewheightforrowatindexpath

How can I modify the heightForRowAtIndexPath so that it adjust height to the textview in it,but also keep the minimum height when textview is empty?


I have a tableView with static cells inside. One cell contains a map, UITextView and other controls:

enter image description here

This textview has the following constraints:

enter image description here

So far I set up the heightForRowAtIndexPath to the static value for this cell:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    if indexPath.row == 0 {
        return 311;
    }
}

but then when the text is longer, the textview - instead of growing - contains the text inside and user has to scroll it. Basically it is always 311 in height. I want to change it, so that the whole cell adjust to the textView content.

I tried changing return 311 to return UITableViewAutomaticDimension, but then, when there's no text, the cell shrinks and the controls on the right are not visible.

So my question is - how can I set dynamic height for the cell based on the text inside, but also keep the minimum height of 311?


Solution

  • If you are simply displaying the text and not editing it in any way. You should try using a UILabel and the UITableViewAutomaticDeminsions will work as expected with that provided the constraints are correctly added.

    What you can do is add a height constraint to the textView and then increase its size based on the size of the string you obtain. Of course you will need to call layoutIfNeeded too! UITableViewAutomaticDimensions should take care of the rest.