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 ?
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];
Since OS X 10.11 in the new NSCollectionView you should use instead:
[self.collectionView scrollToItemsAtIndexPaths:[self.collectionView selectionIndexPaths] scrollPosition:NSCollectionViewScrollPositionCenteredHorizontally];
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)
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)
}
}