How to check if UILabel is truncated?

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

    SWIFT 5

    Example for a multiple lined UILabel that is set to display only 3 lines.

        let labelSize: CGSize = myLabel.text!.size(withAttributes: [.font: UIFont.systemFont(ofSize: 14, weight: .regular)])
    
        if labelSize.width > myLabel.intrinsicContentSize.width * 3 {
            // your label will truncate
        }
    

    Though the user may select the return key adding an extra line without adding to the "text width" in that case something like this may also be useful.

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    
        if text == "\n" {
            // return pressed 
    
        }
    }
    
    0 讨论(0)
  • 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
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题