简体   繁体   中英

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. I'd like to know how many lines the string is taking up in the 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)


You may use the NSLayoutManager of the UITextView to help you compute stuff like that

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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