How to set the tableview cell height Dynamically?

188 views Asked by At

I'm working with Tableview in Swift Now I got an issue with tableview cell height .I'm working on the chat Screen so I have text, Image. so I took one prototype cell within that I'm managing the screen. Now below is my Code for Height

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if msg_type == "Image"  {
        return 150
    }else if msg_type == "Text"{
        return UITableViewAutomaticDimension

    }
}

so text cell not getting as I expected, But here I don't know where is my mistake, and one more thing if I return UITableViewAutomaticDimension it is working fine for Text messages, not images. Please help me thanks in advance.

1

There are 1 answers

9
Shehata Gamal On

Make height dynamic like this

1- put this in viewDidLoad

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

2- before return cell in cellForRow

    cell.layoutSubviews()

    cell.layoutIfNeeded()

3- hook constraints properly from top to bottom in cell xib or storyboard prototype

so , whether it's a cell containing a fixed height image like what you want 150 Or a multi line text it will be layouted properly

4- don't implement heightForRowAt