2

I want to set the number of lines property to 7 and see if my current text is all visible within the 7 lines or not. if its not then i will show a button below which will set the number of lines to 0 at the press of it. The UIlable exists inside a table cell, auto layout will adjust the size.

How can i check if my text is being truncated in the uilable or not? like if it exceeds the 7 lines or not. (the text can contain any combination of new lines and text, so i cant just count the newlines or number of characters, it will have be approximate, but not equal to 7 lines.)

  • 2
    Why not set it to 0 in the first place? – Sweeper Oct 31 '17 at 07:14
  • 1
    the text can be a lot, so there will have to be a lot of scrolling if the text is a lot... so its more convenient to press read more to expand the text and press the button again (with changed title read less) to contract it back to original size. – Taimoor Abdullah Khan Oct 31 '17 at 07:19

1 Answers1

0

Suppose you have set 2 as numberOfLines, so you can check whether the lines are exceeding:

extension UILabel {
    
    func countLabelLines() -> Int {
        // Call self.layoutIfNeeded() if your view is uses auto layout
        let myText = self.text! as NSString
        let attributes = [NSAttributedString.Key.font : self.font]
        
        let labelSize = myText.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))
    }
    
    func isTruncated() -> Bool {
        guard numberOfLines > 0 else { return false }
        return countLabelLines() > numberOfLines
    }
}

usage:

if titleLbl.countLabelLines() > 2 {
    print("Truncating")
}
Charlie
  • 5
  • 7