问题
I'm trying to get the amount of lines in a TextView
. I've searched here for a solution, basically every thread has the same answer : contentheight/fontlineheight.
I have a TextView
with 8 lines, i run this code and i get contsize : 1.944413
NSLog(@"contsize : %f", descLabel.contentSize.height/descLabel.font.lineHeight);
What am i doing wrong?
回答1:
For iOS7, a version that take care that you can have differents font (and font size) in your UITextView :
- (NSUInteger)numberOfLinesInTextView:(UITextView *)textView
{
NSLayoutManager *layoutManager = [textView layoutManager];
NSUInteger index, numberOfLines;
NSRange glyphRange = [layoutManager glyphRangeForTextContainer:[textView textContainer]];
NSRange lineRange;
for (numberOfLines = 0, index = glyphRange.location; index < glyphRange.length; numberOfLines++){
(void) [layoutManager lineFragmentRectForGlyphAtIndex:index
effectiveRange:&lineRange];
index = NSMaxRange(lineRange);
}
return numberOfLines;
}
来源:https://stackoverflow.com/questions/22300297/uitextview-count-lines-not-working-as-intended