Move selection sequentially in NSCollectionView

890 views Asked by At

By default selection in NSCollectionView get moved by arrow keys within one row (or column).

How to make selection move sequentially, like items arranged by index?

Screenshot from developer.apple.com

1

There are 1 answers

1
modusCell On BEST ANSWER

I have asked same question to Apple Developer Technical Support, after checked they said "Our engineers have reviewed your request and have determined that this would be best handled as a bug report.". I submitted bug report to Apple's radar. So far no response.

I decided to implement my own solution. Subclass your NSCollectionView and override keyDown event.

Swift 4

override func keyDown(with event: NSEvent) {
    if event.modifierFlags.rawValue == 10617090 {
        return
    }
    if event.isARepeat == true && event.keyCode != 123 && event.keyCode != 124 && event.keyCode != 125 && event.keyCode != 126 {
        return
    }
    if event.keyCode == 123 || event.keyCode == 124 || event.keyCode == 125 || event.keyCode == 126 {
        for index in self.selectionIndexes {
            if event.keyCode == 124 && index < YOUR_DATASOURCE_ARRAY.count - 1 {
                self.deselectItems(at: [NSIndexPath(forItem: index, inSection: 0) as IndexPath])
                self.selectItems(at: [NSIndexPath(forItem: index + 1, inSection: 0) as IndexPath], scrollPosition: NSCollectionView.ScrollPosition.nearestHorizontalEdge)
                return
            }
            if event.keyCode == 123 && index > 0 {
                self.deselectItems(at: [NSIndexPath(forItem: index, inSection: 0) as IndexPath])
                self.selectItems(at: [NSIndexPath(forItem: index - 1, inSection: 0) as IndexPath], scrollPosition: NSCollectionView.ScrollPosition.nearestHorizontalEdge)
                return
            }
        }
    }
    super.keyDown(with: event)
}

This interrupts left and right arrow key inputs and move selection to previous/next cell. Since "Allows Multiple Selection" has to be NO. Also disable modifier keys as like CMD or Control.

If you keep pressing right arrow, when selection arrives to last cell at right hand it jump one row down and keep moving or vice versa for left arrow. Hope it helps.