Monday, January 28, 2019

How to make ios UITableViewCell automatically resize based on content in label text

Usually the rows in UITableViewCell have fixed height based on cell prototype constraint design, however, sometimes, certain cell may include a large blob of text, such as term and conditions, privacy policy, etc, so the cell height needs to be automatically resized to fit the content.

The below code is required to automatically resize a default UITableViewCell object's height:

\\override two tableview callback methods
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

\\when creating the cell with long text content, set numberOfLine property to 0 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  
     var cell : UITableViewCell? = nil
     if (indexPath.row==1){
        
                cell = UITableViewCell()
                cell?.textLabel?.text = "Terms and Condition\r\n" +
                   "This is a long text string.\r\n" +
                   "This is a long text string.\r\n" +
                   "This is a long test string"
                cell?.textLabel?.numberOfLines = 0;
            }
     }
     return cell!

    }


No comments:

Post a Comment