How to find actual number of lines of UILabel?

前端 未结 14 2411
灰色年华
灰色年华 2020-11-27 13:10

How can I find the actual number of lines of a UILabel after I have initialized it with a text and a font? I have set

14条回答
  •  感动是毒
    2020-11-27 13:49

    None of these worked for me. Below one did,

    Swift 4.2:

    extension UILabel {
        func calculateMaxLines() -> Int {
            let maxSize = CGSize(width: frame.size.width, height: CGFloat(Float.infinity))
            let charSize = font.lineHeight
            let text = (self.text ?? "") as NSString
            let textSize = text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
            let linesRoundedUp = Int(ceil(textSize.height/charSize)) 
            return linesRoundedUp
        }    
    }
    

    Swift 4/4.1:

    extension UILabel {
    
        func calculateMaxLines() -> Int {
            let maxSize = CGSize(width: frame.size.width, height: CGFloat(Float.infinity))
            let charSize = font.lineHeight
            let text = (self.text ?? "") as NSString
            let textSize = text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
            let linesRoundedUp = Int(ceil(textSize.height/charSize)) 
            return linesRoundedUp
        }
    
    }
    

    Swift 3:

    extension UILabel {
    
        func calculateMaxLines() -> Int {
            let maxSize = CGSize(width: frame.size.width, height: CGFloat(Float.infinity))
            let charSize = font.lineHeight
            let text = (self.text ?? "") as NSString
            let textSize = text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
            let linesRoundedUp = Int(ceil(textSize.height/charSize)) 
            return linesRoundedUp
        }
    
    }
    

提交回复
热议问题