Re: Counting lines
Re: Counting lines
- Subject: Re: Counting lines
- From: Douglas Davidson <email@hidden>
- Date: Fri, 11 Oct 2002 12:10:48 -0700
On Friday, October 11, 2002, at 11:48 AM, Max Seelemann wrote:
I thought a while about it but I had no idea, how to solve it...
I've got an NSTextView which auto-breaks the lines. (normal)
And I want to know how many lines there are.
Not how much returns, how much lines.
From one of my previous posts:
Hello, I need to figure out how many lines of text are currently being
displayed in an NSTextView. I've tried all the built-in functions I
can find,
but none of them are giving me the right numbers. I'm pretty new to
this, so
I might have missed something, or be using something wrong.
Do you want the number of hard line breaks, or the number of wrapped
lines?
If the former (this is what the text system would think of as the
"number of paragraphs") you could use Foundation methods like
getLineStart:end:contentsEnd:forRange: and lineRangeForRange:. For
example, you could obtain the number of lines in a string with
something like this:
unsigned numberOfLines, idx, length = [string length];
for (idx = 0, numberOfLines = 0; idx < length; numberOfLines++)
idx = NSMaxRange([string lineRangeForRange:NSMakeRange(idx, 0)]);
These methods take into account a variety of different hard line
breaks, including carriage return, newline, etc.
If the latter, then you can obtain that information from the layout
manager. For example, you could use something like this (not tested,
but should be close)
NSLayoutManager *layoutManager = [textView layoutManager];
unsigned numberOfLines, idx, numberOfGlyphs = [layoutManager
numberOfGlyphs];
NSRange lineRange;
for (numberOfLines = 0, idx = 0; idx < numberOfGlyphs;
numberOfLines++) {
(void)[layoutManager lineFragmentRectForGlyphAtIndex:idx
effectiveRange:&lineRange];
idx = NSMaxRange(lineRange);
}
This will cause layout of the entire text. This will give you the
number of lines needed to lay out the text, no matter how many text
views/text containers it takes to lay it out. For simple scenarios
these are the same, but (for example) in TextEdit's wrap to page mode,
this would give you the number of lines in all pages, not the number
of lines in a single page. To obtain the number of lines in a single
page, you would use glyphRangeForTextContainer: and restrict the above
code to that range rather than using all of (0, numberOfGlyphs).
Douglas Davidson
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.