Re: Get the number of lines of text in an NSTextView?
Re: Get the number of lines of text in an NSTextView?
- Subject: Re: Get the number of lines of text in an NSTextView?
- From: Douglas Davidson <email@hidden>
- Date: Tue, 24 Jan 2006 15:42:07 -0800
On Jan 24, 2006, at 3:34 PM, Todd Ditchendorf wrote:
I've just found the following code snippet in Apple's docs... it
does the trick. I was thinking that some internal structure might
track the number of lines, but between what you're saying and the
fact that this mini-algorithm is in the apple docs, that there's no
such animal. Can anyone confirm/deny?
NSString *s = [aTextView string];
unsigned numberOfLines, index, stringLength = [s length];
for (index = 0, numberOfLines = 0; index < stringLength;
numberOfLines++) {
index = NSMaxRange([s lineRangeForRange:NSMakeRange(index,
0)]);
}
return numberOfLines;
No internal structure tracks the number of lines. That code should
do it. Note that there are other related methods such as
getLineStart:end:contentsEnd:forRange:, paragraphRangeForRange:, and
getParagraphStart:end:contentsEnd:forRange: that you may want if you
are doing something more than just counting lines.
The difference between lineRangeForRange: and
getLineStart:end:contentsEnd:forRange: is that the latter will also
tell you where the trailing line break is (if there is one) and how
long it is, since it may be 0 characters (if the last line has no
trailing line break), 1 character (for \r, \n, etc.) or 2 characters
(for \r\n).
The difference between the "line" methods and the "paragraph" methods
is that there are characters that count as line breaks but not
paragraph breaks, most notably the Unicode line separator U+2028.
This corresponds roughly to the difference between <p> and <br> in HTML.
Douglas Davidson
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden