From 1e39582a46354fe08312cc4ce5b9c71fe3ea9e60 Mon Sep 17 00:00:00 2001 From: James Magahern Date: Tue, 9 Mar 2021 11:21:00 -0800 Subject: [PATCH] Finish implementing autocomplete keyboard nav --- .../AutocompleteViewController.swift | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/App/Autocomplete/AutocompleteViewController.swift b/App/Autocomplete/AutocompleteViewController.swift index 52e8ba4..7a9a7e4 100644 --- a/App/Autocomplete/AutocompleteViewController.swift +++ b/App/Autocomplete/AutocompleteViewController.swift @@ -67,6 +67,53 @@ class AutocompleteViewController: UIViewController, UICollectionViewDelegate self.view = autocompleteView } + override var keyCommands: [UIKeyCommand]? { + [ + UIKeyCommand(action: #selector(self.selectNextItem), input: UIKeyCommand.inputDownArrow), + UIKeyCommand(action: #selector(self.selectPreviousItem), input: UIKeyCommand.inputUpArrow), + UIKeyCommand(action: #selector(self.commitSelectedItem), input: "\r"), // this is stupid... + ] + } + + override func becomeFirstResponder() -> Bool { + let result = super.becomeFirstResponder() + if result { + let firstIndex = IndexPath(row: 0, section: 0) + collectionView.selectItem(at: firstIndex, animated: false, scrollPosition: .top) + } + + return result + } + + private func selectItem(inDirection direction: Int) { + if let selectedIndex = collectionView.indexPathsForSelectedItems?.first { + let nextRow = (selectedIndex.row + direction) + if nextRow < dataSource.snapshot().numberOfItems && nextRow >= 0 { + let nextIndexPath = IndexPath(row: nextRow, section: 0) + collectionView.selectItem(at: nextIndexPath, animated: false, scrollPosition: .centeredVertically) + } + } + } + + @objc + private func selectNextItem(_ sender: Any?) { + selectItem(inDirection: 1) + } + + @objc + private func selectPreviousItem(_ sender: Any?) { + selectItem(inDirection: -1) + } + + @objc + private func commitSelectedItem(_ sender: Any?) { + if let selectedIndex = collectionView.indexPathsForSelectedItems?.first, + let item = dataSource.itemIdentifier(for: selectedIndex) + { + delegate?.autocompleteController(self, didSelectHistoryItem: item) + } + } + // MARK: UICollectionViewDelegate func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {