UITextView count lines not working as intended

送分小仙女□ 提交于 2019-12-12 06:38:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!