I want to add line-numbers to my uitextview. Do I have to write my own UI-Element? Or is there an other solition? Thanks for help!
It might be easier to subclass UITextView and edit the drawing methods there, although it will probably be a chore from any angle.
JoePasq
2010-05-14 17:29:03
+1
A:
I had a similar requirement where I had to display the line number that the end-user's caret was at. This should probably help you (I did it from the view-controller):
- (NSUInteger)lineNumberFromCharacterIndex:(NSUInteger)aCharacterIndex
{
NSLayoutManager* layoutManager = [scriptTextView layoutManager];
NSUInteger numberOfLines = 0;
NSUInteger glyphIndex = [layoutManager glyphIndexForCharacterAtIndex:aCharacterIndex] + 1;
NSUInteger numberOfGlyphs = [layoutManager numberOfGlyphs];
if (glyphIndex > numberOfGlyphs) {
glyphIndex = numberOfGlyphs;
}
NSString* scriptText = [scriptTextView string];
NSUInteger scriptTextLength = [scriptText length];
if (scriptTextLength > 0 && aCharacterIndex >= scriptTextLength && [scriptText characterAtIndex:scriptTextLength - 1] == '\n') {
// Add 1 to the number of lines as the last bit of text is a carriage return and
// the caret will be on the whitespace in the text view after the last character
numberOfLines++;
}
NSRange lineRange;
for (NSUInteger currentGlyphIndex = 0; currentGlyphIndex < glyphIndex; numberOfLines++){
[layoutManager lineFragmentRectForGlyphAtIndex:currentGlyphIndex
effectiveRange:&lineRange];
currentGlyphIndex = NSMaxRange(lineRange);
}
if (numberOfLines == 0) {
numberOfLines = 1;
}
return numberOfLines;
}
Lyndsey Ferguson
2010-05-24 19:43:46