Mina Makar
Mina Makar

Reputation: 51

How to change detailTextLabel height programmatically

I programmed an array into a tableView. When the cell utilizes more than one line for the detailTextLabel, the space in between the lines is small. I would like to know if there is any way to increase this height programmatically? Here is sample code I am using for the array.

cell.textLabel?.text = self.filtered[indexPath.row].coptic
cell.detailTextLabel?.text = self.filtered[indexPath.row].english
cell.textLabel?.font = UIFont(name:"CS Avva Shenouda", size:30)
cell.detailTextLabel?.font = UIFont(name: "Constantia", size:25)
cell.textLabel?.numberOfLines = 0
cell.detailTextLabel?.numberOfLines = 0
cell.detailTextLabel?.textColor = UIColor.darkGray

return cell

Upvotes: 2

Views: 687

Answers (2)

Swathi
Swathi

Reputation: 115

The table view needs to have an estimatedRowHeight and the tableView height as UITableViewAutomaticDimension.

Upvotes: 2

iPatel
iPatel

Reputation: 47099

I'm just putting my logic, not whole code. You can get height of string by below code

func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return ceil(boundingBox.height)
    }

Change cellForRowAtIndexPath Method

cell.detailTextLabel?.numberOfLines = 0 
let height = height(withConstrainedWidth:200, font:YourFont) // change width and font as per your requirement 
cell.detailTextLabel?.frame = CGRect(x: cell.detailTextLabel?.frame.origin.x, y: cell.detailTextLabel?.frame.origin.y, width: cell.detailTextLabel?.frame.size.width, height: height)

You can manage cell height according to detailTextLabel height

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
   return 50 // You should put your code or logic that dynamic height based on heigh of label.
}

Upvotes: 2

Related Questions