How to programmatically select an object (and show this object as selected) in the new NSCollectionView?

I successfully executed NSCollectionView 10.11 on my Mac application. It displays 10 items that I want, but I want the first item to be automatically selected when the application starts.

I tried the following in viewDidLoad and, alternatively, in the viewDidAppear functions;

let indexPath = NSIndexPath(forItem: 0, inSection: 0)
var set = Set<NSIndexPath>()
set.insert(indexPath)
collectionView.animator().selectItemsAtIndexPaths(set, scrollPosition:   NSCollectionViewScrollPosition.Top)

I tried line 4 above and without animator

I also tried the following instead of line 4

collectionView.animator().selectionIndexPaths = set

with and without animator ()

While both of them include an index path in the selected index routes, neither of them displays the selected item.

Any clues I'm wrong about?

+4
source share
1 answer

. Swift 3 viewDidLoad

    // select first item of collection view
    collectionView(collectionView, didSelectItemsAt: [IndexPath(item: 0, section: 0)])
    collectionView.selectionIndexPaths.insert(IndexPath(item: 0, section: 0))

, .

        collectionView.selectItems(at: [IndexPath(item: 0, section: 0)], scrollPosition: NSCollectionViewScrollPosition.top)

NSCollectionViewDelegate

    func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
    // if you are using more than one selected item, code has to be changed
    guard let indexPath = indexPaths.first
        else { return }
    guard let item = collectionView.item(at: indexPath) as? CollectionViewItem
        else { return }
    item.setHighlight(true)
}
+1

Source: https://habr.com/ru/post/1627330/


All Articles