Question

I programmatically select a item in my NSCollectionView. The item is selected as expected but the view doesn't scroll automatically to this item.

[collectionView setSelectionIndexes:[NSIndexSet indexSetWithIndex:compt]];

How to scroll to the selected item ?

Was it helpful?

Solution

Find the answer here NSScrollView: Make sure frame is visible

This code worked for me :

NSRect selectionRect = [self.collectionView frameForItemAtIndex:[[self.collectionView selectionIndexes] firstIndex]];
[self.collectionView scrollRectToVisible:selectionRect];

OTHER TIPS

Since OS X 10.11 in the new NSCollectionView you should use instead:

[self.collectionView scrollToItemsAtIndexPaths:[self.collectionView selectionIndexPaths] scrollPosition:NSCollectionViewScrollPositionCenteredHorizontally];

Tested on: Swift 4.2. Xcode 10.2. macOS 10.14.5 Beta

if  let indexPath = indexPaths.first {
            if #available(OSX 10.12, *) {
                NSAnimationContext.runAnimationGroup { (context) in
                    context.duration = 0.8
                    context.allowsImplicitAnimation = true
                    collectionView.scrollToItems(at: [indexPath], scrollPosition: NSCollectionView.ScrollPosition.bottom)
                }
            } else {
                collectionView.scrollToItems(at: [indexPath], scrollPosition: NSCollectionView.ScrollPosition.bottom)
            }
        }

let scrollPositionX: CGFloat = videoThumbCollectionView.visibleRect.origin.x + 150.0 videoThumbCollectionView.scroll(NSPoint(x: scrollPositionX, y: videoThumbCollectionView.visibleRect.origin.y))

For Swift 4

collectionView.scrollToItems(at: [collectionView.selectionIndexPaths.first!], scrollPosition: NSCollectionView.ScrollPosition.centeredHorizontally)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top