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.