Counting the number of lines in a UITextView, lines wrapped by frame size Counting the number of lines in a UITextView, lines wrapped by frame size ios ios

Counting the number of lines in a UITextView, lines wrapped by frame size


You need to use the lineHeight property, and font lineHeight:

Objective-C

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

Swift

let numLines = (txtview.contentSize.height / txtview.font.lineHeight) as? Int

I am getting correct number of lines.


This variation takes into account how you wrap your lines and the max size of the UITextView, and may output a more precise height. For example, if the text doesn't fit it will truncate to the visible size, and if you wrap whole words (which is the default) it may result in more lines than if you do otherwise.

UIFont *font = [UIFont boldSystemFontOfSize:11.0];CGSize size = [string sizeWithFont:font                       constrainedToSize:myUITextView.frame.size                       lineBreakMode:UILineBreakModeWordWrap]; // default modefloat numberOfLines = size.height / font.lineHeight;


Swift extension:

Using @himanshu padia answer

//MARK: - UITextViewextension UITextView{    func numberOfLines() -> Int{        if let fontUnwrapped = self.font{            return Int(self.contentSize.height / fontUnwrapped.lineHeight)        }        return 0    }}

Usage : yourTextView.numberOfLines()

be aware that if for some reason the font of the text view is nil, the return will be zero.