How to find actual number of lines of UILabel?

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

    It seems that the official developer website mentions one solution Counting Lines of Text in Objc. However, it assumes you have a reference to a text view configured with a layout manager, text storage, and text container. Unfortunately, UILabel doesn't expose those to us, so we need create them with the same configuration as the UILabel.

    I translated the Objc code to swift as following. It seems work well for me.

    extension UILabel {
        var actualNumberOfLines: Int {
            let textStorage = NSTextStorage(attributedString: self.attributedText!)
            let layoutManager = NSLayoutManager()
            textStorage.addLayoutManager(layoutManager)
            let textContainer = NSTextContainer(size: self.bounds.size)
            textContainer.lineFragmentPadding = 0
            textContainer.lineBreakMode = self.lineBreakMode
            layoutManager.addTextContainer(textContainer)
    
            let numberOfGlyphs = layoutManager.numberOfGlyphs
            var numberOfLines = 0, index = 0, lineRange = NSMakeRange(0, 1)
    
            while index < numberOfGlyphs {
                layoutManager.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange)
                index = NSMaxRange(lineRange)
                numberOfLines += 1
            }
            return numberOfLines
        }
    }
    

提交回复
热议问题