How to find actual number of lines of UILabel?

前端 未结 14 2391
灰色年华
灰色年华 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 14:03

    Swift 5.2

    The main point to make it work for me was to call label.layoutIfNeeded() because I was using autoLayout, otherwise it doesnt work.

    func actualNumberOfLines(label: UILabel) -> Int {
            // You have to call layoutIfNeeded() if you are using autoLayout
            label.layoutIfNeeded()
    
            let myText = label.text! as NSString
    
            let rect = CGSize(width: label.bounds.width, height: CGFloat.greatestFiniteMagnitude)
            let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: label.font as Any], context: nil)
    
            return Int(ceil(CGFloat(labelSize.height) / label.font.lineHeight))
        }
    

    Credits to: https://gist.github.com/fuxingloh/ccf26bb68f4b8e6cfd02, which provided the solution in an older swift version, and for mentioning the importance of layoutIfNeeded().

提交回复
热议问题