Saving and restoring NSTextView's position
Asked Answered
C

1

7

I want to be able to save the current text and visible region of an NSTextView and restore it. Using visibleRect and scrollRectToVisible: seems to deliver inconsistent results. If I just do:

- (void)restorePosition
{
    NSRect r = [self.textView visibleRect];

    [self.textView.layoutManager replaceTextStorage: self.textView.textStorage];
    [self.textView scrollRectToVisible: r];
}

the view will stay in position when the view is positioned less than 85 lines from the top, but the further down I go the further off it becomes. At 200 lines from the top it ends up at 277, at 300 it ends up at 408 etc.

Without the replaceTextStorage it works as expected too, but replacing the text and finding the previous place is the whole point. Something about replacing the text causes the line rectangle calculations to go wonky.

Obviously I'm planning to get the new visibleRect and textStorage from a saved object in the real app, but this illustrates the problem with the minimum code.

Any ideas?

Clipped answered 11/4, 2013 at 18:48 Comment(1)
I have found that using NSLayoutManager *layoutManager = myTextView.layoutManager; NSRange glyphRange = [layoutManager glyphRangeForBoundingRect: [self.textView visibleRect] inTextContainer: self.textView.textContainer]; NSRange charRange = [layoutManager characterRangeForGlyphRange: glyphRange actualGlyphRange: &glyphRange]; to save the position and ` [myTextView scrollRangeToVisible: charRange];` to restore almost works. It can be off by a line but that is much better than scrollRectToVisible: does.Clipped
M
4

I had a similar problem relating to restoring scroll position. For me the solution was to force the text view to layout before changing the visible rect:

[textView.layoutManager ensureLayoutForTextContainer:textView.textContainer];
Marcellmarcella answered 22/6, 2017 at 16:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.