'How to make tableview row and label height according to label text in swift?

I am making chat related screen, here i have placed view inside tableview cell and label in side view.

for view and i have given leading, trailing, top, bottom

for label i have given leading, trailing, top, bottom constraints

but here cell and label text not coming well, sometime for short text cell becomes big and for long text it remains same like below its coming

enter image description here

here is the code:

   func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
   {
    if indexPath.section==0 {
        if (indexPath.row%2)==0
        {
            let cell:ReceiverChatTableViewCell = (chatTableView.dequeueReusableCell(withIdentifier: "ReceiverChatTableViewCell") as! ReceiverChatTableViewCell?)!

            let font = UIFont(name: "Helvetica", size: 20.0)

            var height = heightForView(text: cell.receiverTextLbl.text!, font: font!, width: 100.0)

            if height<60
            {
                height=60
            }

            return height
        } 
    }

    else
    {
        return 50
    }
    return UITableView.automaticDimension
  }


 func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 1000
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text

    label.sizeToFit()

    return label.frame.height
}

please help me to solve the code.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source