swiftcocoanstableviewappkitnsscrollview

Preserving (and loading) table view scroll position for each data source


I am trying to replicate Mail.app behaviours in my app. If you have multiple e-mail accounts and select a random e-mail for each account and switch between each account from the sidebar, the app remembers your scroll position and which e-mail you selected and display them accordingly. That is what I want in my app.

I know how to preserve the row selection, that is easy. tableView.selectedRowIndexes

My tableView has multiple data sources and switches (tableView.reloadData()) accordingly from the sidebar.

I am having a major problem with the scroll position. I tried looking into NSScrollView, NSClipView and NSTableView. It seems to me that there are scrolling mechanism for each view.

  1. I need to remember the scroll position when the user scroll for each data source
  2. I need to load the previous scroll position when the user return to the data source

Also a strange behaviour I noticed is when reloading tableView to a different data source, it seems to persistently remember from the previous data source scroll position. Is that normal? I assumed it would reset to the top.

My data sources are arrays which are my NSViewController subclass properties.

If it matters, I am using storyboard, my app is targeting Big Sur and I am using Swift.


Solution

  • The position to save:

    preservedPosition = tableView.visibleRect.origin
    

    Restore:

    tableView.scroll(preservedPosition)