7

When moving from line to line in a textview with "up" and "down" keys, it exhibits this scrolling behavior - when the cursor is at the very top and I hit "up" (and vice versa), it scrolls the document half page up, that is, the current line is now in the middle of the textview.

Is it possible to disable this behavior? Is it possible to make it scroll by just one line? So that the current line stays always at the top (or bottom)?

Ecir Hana
  • 10,864
  • 13
  • 67
  • 117

2 Answers2

2

I know I come a little late to the party, but since this hasn't been properly answered, I'll give it a try. I had the same problem with NSTextViews. When using -scrollRangeToVisible to bring the insert position to the visible rect of the view, it had this habit of scrolling as to put the caret in the (vertical)middle of the screen. What I did was use [NSView scrollRectToVisible] instead, as it scrolls the minimum distance needed to bring a rect to the visible rect of the view:

NSRange caretRng = NSMakeRange(caretLocation, 0);
NSLayoutManager* lm = [view layoutManager];
NSRange glyphRange = [lm glyphRangeForCharacterRange:caretRng actualCharacterRange:nil];
NSRect glyphRect = [lm boundingRectForGlyphRange:glyphRange inTextContainer:[view textContainer]];
[view scrollRectToVisible:glyphRect];

Hope it helps!

ipmcc
  • 29,581
  • 5
  • 84
  • 147
Ibazan
  • 66
  • 2
  • Thanks! But where should I put this im my NSTextView subclass? I understand that `scrollRectToVisible:` scrolls the way I want - the problem is, NSTextView seems to call `scrollRangeToVisible:` - how to make it call the former method? – Ecir Hana Feb 21 '13 at 15:21
  • Have you tried overriding ScrollRangeToVisible in your NSTextView subclass? In my setup I override keyDown messages and do caret motions manually, so scrollRangeToVisible is not automatically called and I can call scrollRectToVisible manually, but that should do it, although I don't know about possible side effects. – Ibazan Feb 21 '13 at 18:01
  • It more-or-less works! The only issue is that sometimes, when I hold up/down arror pressed for longer time, it misses to scroll a few rows so the caret is not in the very first/last row but maybe 2-3 lines below/above it. – Ecir Hana Feb 22 '13 at 10:41
  • Sorry I can't help you any further, I'm an Obj-C/Cocoa beginner myself. – Ibazan Feb 23 '13 at 15:08
  • Hi, what's the value of caretLocation? and view? I tried to use this in a NSTextView but it gives an error... –  Mar 08 '16 at 10:49
1

NSTextView (via NSText) has a method called -scrollRangeToVisible:. Consider subclassing NSTextView and overriding -scrollRangeToVisible to specify your own scrolling behavior directly.

If you need more specific help with getting the behavior right, post a separate question specifying exactly the behavior you want and the code you tried to get it.

Joshua Nozzi
  • 60,946
  • 14
  • 140
  • 135