How to find actual number of lines of UILabel?

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

    Note that @kurt-j's answer will not always work. In some cases, you will have to manually provide the width of label. Since these cases exist, it is a good idea to have an optional width parameter, even if you don't end up using it.

    Swift 4.2:

    extension UILabel {
        func calculateMaxLines(actualWidth: CGFloat?) -> Int {
            var width = frame.size.width
            if let actualWidth = actualWidth {
                width = actualWidth
            }
            let maxSize = CGSize(width: 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
        }    
    }
    

提交回复
热议问题