How to check if UILabel is truncated?

前端 未结 20 2684
不知归路
不知归路 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 
    
        }
    }
    

提交回复
热议问题