Autocomplete UI

This commit is contained in:
James Magahern
2020-09-21 17:56:22 -07:00
parent 7f2cd23889
commit e2d5dbee59
5 changed files with 155 additions and 5 deletions

View File

@@ -0,0 +1,73 @@
//
// AutocompleteViewController.swift
// App
//
// Created by James Magahern on 9/21/20.
//
import UIKit
protocol AutocompleteViewControllerDelegate: class {
func autocompleteController(_: AutocompleteViewController, didSelectHistoryItem: HistoryItem)
}
class AutocompleteViewController: UIViewController, UICollectionViewDelegate
{
public var historyItems: [HistoryItem] = [] {
didSet {
var snapshot = dataSource.snapshot()
snapshot.deleteAllItems()
snapshot.appendSections([ .HistoryItems ])
snapshot.appendItems(historyItems, toSection: .HistoryItems)
dataSource.apply(snapshot, animatingDifferences: false)
}
}
public weak var delegate: AutocompleteViewControllerDelegate?
private enum Section: Int {
case HistoryItems
}
public let collectionView: UICollectionView
private let dataSource: UICollectionViewDiffableDataSource<Section, HistoryItem>
init() {
let listConfiguration = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
let listLayout = UICollectionViewCompositionalLayout.list(using: listConfiguration)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: listLayout)
let cellRegistry = UICollectionView.CellRegistration<UICollectionViewListCell, HistoryItem> { (cell, indexPath, item) in
var config = cell.defaultContentConfiguration()
config.text = item.title
config.secondaryText = item.url.absoluteString
cell.contentConfiguration = config
}
dataSource = UICollectionViewDiffableDataSource<Section, HistoryItem>(collectionView: collectionView, cellProvider:
{ (collectionView, indexPath, item) -> UICollectionViewCell? in
collectionView.dequeueConfiguredReusableCell(using: cellRegistry, for: indexPath, item: item)
})
super.init(nibName: nil, bundle: nil)
collectionView.delegate = self
view.backgroundColor = .systemBackground
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func loadView() {
self.view = collectionView
}
// MARK: UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
if let item = dataSource.itemIdentifier(for: indexPath) {
delegate?.autocompleteController(self, didSelectHistoryItem: item)
}
}
}