NSScrollView: Make sure frame is visible

2019-08-01 02:59发布

问题:

I have an NSCollectionView that lists items from a Core Data source. Each item has a button that when fired slides down an action view. When this view slides down, the collection view shrinks so that both views fit on top of each other in the same window space.

To provide a good user experience I want the NSCollectionViewItem that fired the action to be completely visible. I have it's frame - which I got from -frameForItemAtIndex:.

How can I - using the NSRect frame variable and my scrollView outlet - check if frame is visible in the scrollView and, if it isn't, scroll scrollView so that it is?

回答1:

You should be able to do something like this:

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

Note that you're sending scrollRectToVisible: to the collectionView, not to the scrollView. If the selectionRect is already visible, the call won't do anything.