Get number of lines in UITextView without contentSize.height Get number of lines in UITextView without contentSize.height xcode xcode

Get number of lines in UITextView without contentSize.height


I found the perfect solution to this problem in Apple's Text Layout Programming Guide. The solution Apple provides is in Objective-C, so I tested and re-wrote it for Swift.

Both methods work great and return the exact number of lines that are being used in a UITextView, without funky math and 100% accurate every time.

Here is my extension to UITextView to add a numberOfLines() method:

extension UITextView {    func numberOfLines() -> Int {        let layoutManager = self.layoutManager        let numberOfGlyphs = layoutManager.numberOfGlyphs        var lineRange: NSRange = NSMakeRange(0, 1)        var index = 0        var numberOfLines = 0        while index < numberOfGlyphs {            layoutManager.lineFragmentRectForGlyphAtIndex(                index, effectiveRange: &lineRange            )            index = NSMaxRange(lineRange)            numberOfLines += 1        }        return numberOfLines    }}

Just call this directly on your UITextView like so: myTextView.numberOfLines() <- returns an Int


This extension is also easily converted to a method like so:

func numberOfLines(textView: UITextView) -> Int {    let layoutManager = textView.layoutManager    let numberOfGlyphs = layoutManager.numberOfGlyphs    var lineRange: NSRange = NSMakeRange(0, 1)    var index = 0    var numberOfLines = 0    while index < numberOfGlyphs {        layoutManager.lineFragmentRectForGlyphAtIndex(index, effectiveRange: &lineRange)        index = NSMaxRange(lineRange)        numberOfLines += 1    }    return numberOfLines}

Just call numberOfLines(myTextView) to retrieve an Int of the number of lines


I didn't find a way to get the number of lines, but I managed to remove all that white space using textView.sizeToFit(). It worked great, hopefully someone will find this useful!