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

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 mode
float numberOfLines = size.height / font.lineHeight;

UITextView if line numbers is 2

For Count the number of lines of text

int numLines = textView.contentSize.height / textView.font.lineHeight;
NSLog(@"number of line - %d", numLines);

And for iOS 7 see this Question/Answer.

EDIT for iOS < 7:

This is proper answer

UIFont *myFont = [UIFont boldSystemFontOfSize:13.0]; // your font with size
CGSize size = [textView.text sizeWithFont:myFont constrainedToSize:textView.frame.size lineBreakMode:UILineBreakModeWordWrap]; // default mode
int numLines = size.height / myFont.lineHeight;
NSLog(@"number of line - %d", numLines);

Get number of lines in UITextView without contentSize.height

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!

How to calculate width of multiple lines of UITextview?

try this one

UIFont *font=[UIFont systemFontOfSize:17.0f];

UILabel *yourLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 80)];
yourLabel.numberOfLines=4;
yourLabel.text=@"Hello\nHulo\nMe\nyou";

CGSize labelSize = [yourLabel.text sizeWithFont:font
constrainedToSize:yourLabel.frame.size
lineBreakMode:NSLineBreakByTruncatingTail];
CGFloat singleLineHeight = labelSize.height/yourLabel.numberOfLines;


[self.view addSubview:yourLabel];

A single line height will be about 21.

NSLog(@"single line height is %f",singleLineHeight);

For text View follow this code

UITextView *yourView=[[UITextView alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
yourView.font=[UIFont systemFontOfSize:14.0f];
yourView.text = @"Hello \nmy\n Friend\n Hru? ";

CGSize textViewSize = [yourView.text sizeWithFont:yourView.font
constrainedToSize:CGSizeMake(yourView.frame.size.width, FLT_MAX)
lineBreakMode:NSLineBreakByTruncatingTail];

[yourView setFrame:CGRectMake(0, 0, textViewSize.width, textViewSize.height)];

[self.view addSubview:yourView];

NSLog(@"single line height is %f",yourView.frame.size.height);

UITextView number of lines iOS 7

You can use something like this. It's low performance but this is what I could figure till now.

NSString *string=textView3.text;
NSArray *array=[string componentsSeparatedByString:@"\n"];
NSLog(@"%d",array.count);


Related Topics



Leave a reply



Submit