How to check if UILabel is truncated?

前端 未结 20 2717
不知归路
不知归路 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:38

    Make sure to call either of these in viewDidLayoutSubviews.

    public extension UILabel {
    
        var isTextTruncated: Bool {
            layoutIfNeeded()
            return text?.boundingRect(with: CGSize(width: bounds.width, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font!], context: nil).size.height ?? 0 > bounds.size.height
        }
    
        var isAttributedTextTruncated: Bool {
            layoutIfNeeded()
            return attributedText?.boundingRect(with: CGSize(width: bounds.width, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil).size.height ?? 0 > bounds.size.height
        }
    
    }
    

提交回复
热议问题