Search code examples
iosswiftfontsuilabeltruncate

Swift ios how to find out Label text is truncated or not


Label number of lines to 3 from storyboard

Following is my code to find out label text is truncated or not

 let size = reviewLbl.text?.size(withAttributes: [.font: reviewLbl.font]) ?? .zero
    if (size.height > reviewLbl.frame.size.height) {

    }

Also tried following link but it isn't working for me so don't call this as duplicate question

How to check if UILabel is truncated?


Solution

  •   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 isTruncatedOrNot() -> Bool {
    
        if (self.countLabelLines() > self.numberOfLines) {
            return true
        }
        return false
    }
    

    try this, and self.bound.width is your label width so if you added Label in stack view make sure label width or stackview have proper constraints.
    In your case its returning true every time because it might have constraints issue.