Adjust UITableViewCell Height Based on Text Length

Índice
  1. The Problem
  2. The Solution
  3. Conclusion

The Problem

When working with UITableView in iOS, one common issue is figuring out how to adjust the height of a UITableViewCell based on the length of the text it contains. This is particularly important when dealing with dynamic or user-generated content, where the length of the text can vary widely.

The Solution

Fortunately, there is a relatively simple solution to this problem. First, we need to calculate the height of the text using NSString's boundingRect method. This method returns a CGRect that represents the size required to draw the text with the given font and layout constraints.

Once we have the height of the text, we can update the height of the UITableViewCell using UITableView's heightForRowAtIndexPath method. This method takes an NSIndexPath as an argument and returns the height of the cell at that index path.

To implement this solution, we need to first subclass UITableViewCell and override the layoutSubviews method. In this method, we calculate the height of the text and update the height of the cell. Here's an example implementation:


class DynamicHeightTableViewCell: UITableViewCell {

    func updateCellWithText(text: String) {
        self.textLabel?.text = text
        self.textLabel?.numberOfLines = 0
        self.textLabel?.lineBreakMode = .byWordWrapping
        
        // Calculate height of text
        let textRect = NSString(string: text).boundingRect(with: CGSize(width: self.contentView.frame.size.width - 30, height: CGFloat.greatestFiniteMagnitude),
                                                            options: .usesLineFragmentOrigin,
                                                            attributes: [NSAttributedString.Key.font: self.textLabel?.font ?? UIFont.systemFont(ofSize: 17)],
                                                            context: nil)
        
        // Update cell height
        self.frame.size.height = textRect.size.height + 30
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        if let text = self.textLabel?.text {
            self.updateCellWithText(text: text)
        }
    }
}

We can then use this custom cell class in our UITableView by registering it with the table view and returning the calculated height in the heightForRowAtIndexPath method:


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "DynamicHeightTableViewCell", for: indexPath) as! DynamicHeightTableViewCell
    cell.updateCellWithText(text: self.textArray[indexPath.row])
    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let text = self.textArray[indexPath.row]
    let textRect = NSString(string: text).boundingRect(with: CGSize(width: tableView.frame.size.width - 30, height: CGFloat.greatestFiniteMagnitude),
                                                        options: .usesLineFragmentOrigin,
                                                        attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17)],
                                                        context: nil)
    return textRect.size.height + 30
}

Conclusion

Adjusting the height of a UITableViewCell based on the length of the text it contains is a common requirement when working with dynamic content in UITableView. By subclassing UITableViewCell and calculating the height of the text using NSString's boundingRect method, we can easily update the height of the cell to accommodate the text.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information