How to check if UILabel is truncated?

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

    extension UILabel {
    
    public func resizeIfNeeded() -> CGFloat? {
        guard let text = text, !text.isEmpty else { return nil }
    
        if isTruncated() {
            numberOfLines = 0
            sizeToFit()
            return frame.height
        }
        return nil
    }
    
    func isTruncated() -> Bool {
        guard let text = text, !text.isEmpty else { return false }
    
        let size: CGSize = text.size(withAttributes: [NSAttributedStringKey.font: font])
        return size.width > self.bounds.size.width
        }
    }
    

    You can calculate the width of the string and see if the width is greater than label width.

提交回复
热议问题