How to find UITextView number of lines

3 Solutions Collect From Internet About “How to find UITextView number of lines”

If you are using iOS 3, you need to use the leading property:

int numLines = txtview.contentSize.height / txtview.font.leading;

If you are using iOS 4, you need to use the lineHeight property:

int numLines = txtview.contentSize.height / txtview.font.lineHeight;

And, as @thomas pointed out, be careful of rounding if you need an exact result.

You can look at the contentSize property of your UITextView to get the height of the
text in pixels, and divide by the line spacing of the UITextView’s font to get the
number of text lines in the total UIScrollView (on and off screen), including both wrapped and line broken text.

int numLines = txtview.contentSize.height/txtview.font.leading;

Swift 4 way to calculate number of lines in UITextView using UITextInputTokenizer:

public extension UITextView {
    /// number of lines based on entered text
    public var numberOfLines: Int {
        guard compare(beginningOfDocument, to: endOfDocument).same == false else {
            return 0
        }
        let direction: UITextDirection = UITextStorageDirection.forward.rawValue
        var lineBeginning = beginningOfDocument
        var lines = 0
        while true {
            lines += 1
            guard let lineEnd = tokenizer.position(from: lineBeginning, toBoundary: .line, inDirection: direction) else {
                fatalError()
            }
            guard compare(lineEnd, to: endOfDocument).same == false else {
                break
            }
            guard let newLineBeginning = tokenizer.position(from: lineEnd, toBoundary: .character, inDirection: direction) else {
                fatalError()
            }
            guard compare(newLineBeginning, to: endOfDocument).same == false else {
                return lines + 1
            }
            lineBeginning = newLineBeginning
        }
        return lines
    }
}