Autocomplete UI
This commit is contained in:
73
App/Autocomplete/AutocompleteViewController.swift
Normal file
73
App/Autocomplete/AutocompleteViewController.swift
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user