简体   繁体   English

在UITextView iOS 7中查找行数

[英]Finding the number of lines in a UITextView iOS 7

I've been researching this for hours and have not found a solid answer for this in ios 7. I have a requirement that I need to find out how many lines of text are being displayed in the UITextView. 我已经研究了几个小时,但在ios 7中没有找到一个可靠的答案。我有一个需求,我需要找出UITextView中显示了多少行文本。 I'd like to know how many lines the string is taking up in the UITextView 我想知道该字符串在UITextView中占用了多少行

Here is the string i want to use 这是我要使用的字符串

self.txtView.text = @"Evolving from older bat-and-ball games, an early form of baseball         was being played in England by the mid-18th century. ";

I tried this 我试过了

int numLines = self.txtView.contentSize.height/self.txtView.font.leading;

As well as many other things but it just says the same (incorrect) number every time, even when I change the string. 与许多其他事情一样,但是即使我更改了字符串,每次也只说相同(不正确)的数字。

[EDIT] Answer edited to provide a better solution / code (directly inspired from the Apple doc) [编辑]答案经过编辑以提供更好的解决方案/代码(直接从Apple文档获得启发)


You may use the NSLayoutManager of the UITextView to help you compute stuff like that 您可以使用UITextViewNSLayoutManager来帮助您计算类似的内容

NSLayoutManager *layoutManager = [textView layoutManager];
unsigned nbLines, glyphIndex
unsigned numberOfGlyphs = [layoutManager numberOfGlyphs];
NSRange lineRange;

for (nbLines = 0, glyphIndex = 0; index < numberOfGlyphs; ++nbLines)
{
    [layoutManager lineFragmentRectForGlyphAtIndex:glyphIndex effectiveRange:&lineRange];
    glyphIndex = NSMaxRange(lineRange); // Skip to after last glyph of the line for next iteration
}
NSLog(@"Number of lines: %u", nbLines)

Source & Detailed explanations: Apple's Text Layout Programming Guide: "Counting lines of text" 原始资料和详细说明: Apple的《文本布局编程指南》:“计数文本行”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM