In iOS 6 I used this code to get the number of lines in the UITextView
:
int numLines = textView.contentSize.height / textView.font.lineHeight;
But this is not working in iOS 7. How do I get the total number of lines of the UITextView in iOS 7?
In iOS 6 I used this code to get the number of lines in the UITextView
:
int numLines = textView.contentSize.height / textView.font.lineHeight;
But this is not working in iOS 7. How do I get the total number of lines of the UITextView in 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);
You can do this with the UITextInputTokenizer
/UITextInput
protocol methods of UITextView.
id<UITextInputTokenizer> tokenizer = textView.tokenizer;
UITextPosition *pos = textView.endOfDocument; int lines = 0;
while (true){
UITextPosition *lineEnd = [tokenizer positionFromPosition:pos toBoundary:UITextGranularityLine inDirection:UITextStorageDirectionBackward];
if([textView comparePosition:pos toPosition:lineEnd] == NSOrderedSame){
pos = [tokenizer positionFromPosition:lineEnd toBoundary:UITextGranularityCharacter inDirection:UITextStorageDirectionBackward];
if([textView comparePosition:pos toPosition:lineEnd] == NSOrderedSame) break;
continue;
}
lines++; pos = lineEnd;
}
//lines--; // Compensation for extra line calculated (??)
(GIST)
you can pass the String and textView to this method and it will return the current number rows in this textview even if the user pressed new line:
-(int)numberOfRows:(NSString *)string inView:(UITextView*)txtView
{
CGSize maximumLabelSize = CGSizeMake(MAXFLOAT , MAXFLOAT);
NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin;
NSString *new = [string stringByReplacingOccurrencesOfString: @"\n" withString:@" "];
NSDictionary *attr = @{NSFontAttributeName: [UIFont fontWithName:urFont size:urSize]};
CGRect bounds = [new boundingRectWithSize:maximumLabelSize
options:options
attributes:attr
context:nil];
CGSize viewSize = bounds.size;
int row = floor(txtView.contentSize.height / viewSize.height ) ;
return row;
}