Reputation: 8836
There're already a lot of threads related to this topic, but I never could find a correct way to get line number of UITextView in iOS7 and iOS8. Below is the way that I think it's the best one, but still have some problems when text font is small. Anybody has a better solution?
Step1:Get the text height in UITextView. from: Resize font size to fill UITextView?
- (float) getTextSizeHeight:(UITextView *) textView{
[iConsole info:@"%s",__FUNCTION__];
CGSize tallerSize = CGSizeMake(textView.frame.size.width-16,999);
CGSize stringSize;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
stringSize = [textView.text sizeWithFont:textView.font constrainedToSize:tallerSize lineBreakMode:NSLineBreakByWordWrapping];
} else {
stringSize = [textView.text sizeWithFont:textView.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];
}
CGFloat textHeight = stringSize.height; //textView.contentSize.height is not the right way
return textHeight;
}
Step2: calculate line number
- (int) lineNumberWithUITextView:(UITextView *) textView
{
float textHeight = [self getTextSizeHeight:textView];
float lineHeight = textView.font.lineHeight;
float numLines = textHeight / lineHeight;
int returnVal = ceilf(numLines);
return returnVal;
}
Upvotes: 0
Views: 254
Reputation: 80
in ios7 above,you can use:
float rows = round((textView.contentSize.height - textView.textContainerInset.top - textView.textContainerInset.bottom) / textView.font.lineHeight);
Upvotes: 1