0

I have set number of lines on UILabel as 2, since that's the max number of lines I want to show on UILabel and then any text will get truncated instead of wrapping it on 3rd line.

This UILabel is part of UITableViewCell and I want to change the height of the cell, based on the height of the label or based on the number of lines of text on the label. If the text is one line, then the table view's height will be little smaller than if the text is of 2 lines.

My function to returning the number of lines on a UILabel sometimes returns correct number of lines and sometimes it returns count as 1 even if the text is wrapped to 2 lines.

func isTextWrapped() -> Bool {
   return countOfLabelLines() >= 2
}
    
func countOfLabelLines(honorConstraints: Bool = false) -> Int {
   if let labelText = self.text as NSString? {
   let attributes = [NSAttributedString.Key.font : self.font]
            
    // Needed to consider the constraints on the label.
    if honorConstraints {
        self.layoutIfNeeded()
    }
            
    let labelSize = labelText.boundingRect(with: CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes as [NSAttributedString.Key : Any], context: nil)
        return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
    }
        
    return 0

}

How can I return the correct number of lines displayed on UILabel i.e. 1 if text is not wrapped or 2 if text is wrapped?

I am using a custom table view cell which dequeues using reusable id.

tech_human
  • 6,592
  • 16
  • 65
  • 107
  • No need to count, instead use autolayout and let the label get "bigger", and with a max height, it should be enough. – Larme Mar 11 '22 at 19:35

1 Answers1

0

There is another way to do this if your table view only to display text. Instead of using the height you pass in you can set the table cell height to be dynamic.

More further information you can check the following link: Problems with autoresizing (dynamic height) tableview cells

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
Thang Phi
  • 1,641
  • 2
  • 7
  • 16