Elfoiros
Elfoiros

Reputation: 468

NSCollectionView How to scroll to selected item

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 ?

Upvotes: 3

Views: 4126

Answers (6)

Ely
Ely

Reputation: 9141

If you want to select and scroll with animation at the same time, you can use this (Swift):

 NSAnimationContext.runAnimationGroup { (context) in
     context.allowsImplicitAnimation = true
     collectionView.selectItems(at: [newIndexPath], scrollPosition: .centeredVertically)
 }

Upvotes: 0

Darkwonder
Darkwonder

Reputation: 1315

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

Upvotes: 5

Akshay Phulare
Akshay Phulare

Reputation: 1599

For Swift 4

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

Upvotes: 0

Manee ios
Manee ios

Reputation: 1160

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

Upvotes: 0

EckhardN
EckhardN

Reputation: 509

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

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

Upvotes: 3

Elfoiros
Elfoiros

Reputation: 468

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

Upvotes: 6

Related Questions