How to find UILabel's number of Lines

后端 未结 7 717
悲哀的现实
悲哀的现实 2020-11-28 05:35

I displayed the text in UILabel by using wrap method. Now I want to need to find the how many number of line is there in UILabel.

If there is any possible way to fi

7条回答
  •  自闭症患者
    2020-11-28 06:22

    For iOS7 and above, the officially sanctioned way to count the number of lines is to use TextKit:

    func numberOfLinesForString(string: String, size: CGSize, font: UIFont) -> Int {
        let textStorage = NSTextStorage(string: string, attributes: [NSFontAttributeName: font])
    
        let textContainer = NSTextContainer(size: size)
        textContainer.lineBreakMode = .ByWordWrapping
        textContainer.maximumNumberOfLines = 0
        textContainer.lineFragmentPadding = 0
    
        let layoutManager = NSLayoutManager()
        layoutManager.textStorage = textStorage
        layoutManager.addTextContainer(textContainer)
    
        var numberOfLines = 0
        var index = 0
        var lineRange : NSRange = NSMakeRange(0, 0)
        for (; index < layoutManager.numberOfGlyphs; numberOfLines++) {
            layoutManager.lineFragmentRectForGlyphAtIndex(index, effectiveRange: &lineRange)
            index = NSMaxRange(lineRange)
        }
    
        return numberOfLines
    }
    

提交回复
热议问题