How to check if UILabel is truncated?

前端 未结 20 2780
不知归路
不知归路 2020-11-28 02:53

I have a UILabel that can be varying lengths depending on whether or not my app is running in portrait or landscape mode on an iPhone or iPad. When the text is

20条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 03:29

    Swift 3

    You can count the number of lines after assigning the string and compare to the max number of lines of the label.

    import Foundation
    import UIKit
    
    extension UILabel {
        
        func countLabelLines() -> Int {
            // Call self.layoutIfNeeded() if your view is uses auto layout
            let myText = self.text! as NSString
            let attributes = [NSFontAttributeName : self.font]
            
            let labelSize = myText.boundingRect(with: CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil)
            return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
        }
        
        func isTruncated() -> Bool {
            guard numberOfLines > 0 else { return false }
            return countLabelLines() > numberOfLines
        }
    }
    

提交回复
热议问题