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

By : Abhinav
Source: Stackoverflow.com
Question!

I wanted to know when a text is wrapped by the frame of the text view is there any delimiter with which we can identify whether the text was wrapped or not.

For instance if my text view has a width of 50 px and text is exceeding that, it wraps the text to next line.

I wanted to count the number of lines in my text view. Now "\n" and "\r" are not helping me.

My code is:

NSCharacterSet *aCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"\n\r"];
    NSArray *myArray = [textViewText componentsSeparatedByCharactersInSet:aCharacterSet];
    NSLog(@"%d",[myArray count]);
By : Abhinav


Answers

I found the perfect solution to this problem in Apple's Text Layout Programming Guide. Here is the solution Apple provides:

NSLayoutManager *layoutManager = [textView layoutManager];
unsigned numberOfLines, index;
unsigned numberOfGlyphs = [layoutManager numberOfGlyphs];
NSRange lineRange;

for (numberOfLines = 0, index = 0; index < numberOfGlyphs; numberOfLines++){
    (void) [layoutManager lineFragmentRectForGlyphAtIndex:index effectiveRange:&lineRange];
    index = NSMaxRange(lineRange);
}

This could easily be written into an extension for UITextView, or as a standalone method taking in a UITextView object as a parameter



You need to consider textView.textContainerInset, also need to round the calculated value since line number definitely is an integer

float rawLineNumber = (textView.contentSize.height - textView.textContainerInset.top - textView.textContainerInset.bottom) / textView.font.lineHeight;
int finalLineNumber = round(rawLineNumber)

In real case, you may see following result rawLineNumber = 3.008099 finalLineNumber = 3 (3 lines)

By : Jacky


Swift extension:

Using @himanshu padia answer

//MARK: - UITextView
extension 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.



This video can help you solving your question :)
By: admin