Bob N.
Bob N.

Reputation: 43

Keyboard focus on NSCollectionView when app launches

I'm trying to have keyboard focus on my NSCollectionView when my Mac App launches or when I switch tabs. I've tried making it the firstResponder, and it says that it is when I test, but I have to click inside the collection view before I can use the arrow keys to navigate around the collection view items.

@IBOutlet weak var collectionView: NSCollectionView!

override func viewDidAppear() {
    self.collectionView.item(at: 0)?.isSelected = true
    self.collectionView.becomeFirstResponder()
}

I also tried putting it in viewDidAppear override, but no dice.

Anybody have the same issue? How did you get around it?

Upvotes: 2

Views: 876

Answers (2)

Oleksii Nikolaiev
Oleksii Nikolaiev

Reputation: 61

I did this:

self.collectionView.reloadData()
if let selectionIndexPath = self.selectionIndexPath {
   self.collectionView.selectItems(at: [selectionIndexPath],
                       scrollPosition: .centeredVertically)
   self.view.window?.makeFirstResponder(self.collectionView)
}

NSCollectionView gets focus in this way. (tested on Mac OS 10.15.4). I reloaded data when got response from the back end.

Upvotes: 0

gietal
gietal

Reputation: 139

In my experience, NSCollectionView doesn't let you navigate with arrow keys unless an item is selected already. So I did it by subclassing NSCollectionView.becomeFirstResponder() and manually selecting the first available item when nothing is selected.

class MyCollectionView: NSCollectionView {

    override func becomeFirstResponder() -> Bool {
        if selectionIndexPaths.count == 0 {
            for section in 0..<numberOfSections {
                if numberOfItems(inSection: section) > 0 {
                    selectionIndexPaths = [IndexPath(item: 0, section: section)]
                    break
                }
            }
        }
        return super.becomeFirstResponder()
    }
}

Upvotes: 2

Related Questions