UITextView计数行未按预期工作 [英] UITextView count lines not working as intended

查看:89
本文介绍了UITextView计数行未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取TextView中的行数.我在这里搜索了一个解决方案,基本上每个线程都有相同的答案:contentheight/fontlineheight.

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.

我有一个8行的TextView,运行此代码,我得到contsize : 1.944413

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);

我在做什么错了?

推荐答案

对于iOS7,该版本要注意您可以在UITextView中使用不同的字体(和字体大小):

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;
}

这篇关于UITextView计数行未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆