NSCollectionView How to scroll to selected item

2019-04-10 17:45发布

问题:

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 ?

回答1:

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];


回答2:

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

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


回答3:

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



回答4:

For Swift 4

collectionView.scrollToItems(at: [collectionView.selectionIndexPaths.first!], scrollPosition: NSCollectionView.ScrollPosition.centeredHorizontally)


回答5:

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)
            }
        }