91 lines
3.0 KiB
Swift
91 lines
3.0 KiB
Swift
//
|
|
// CommonControllerAutocomplete.swift
|
|
// PayCash
|
|
//
|
|
// Created by Igor on 10.02.2021.
|
|
//
|
|
|
|
import UIKit
|
|
|
|
class CommonControllerAutocomplete: UIViewController {
|
|
|
|
@IBOutlet private weak var tableView: UITableView!
|
|
@IBOutlet private weak var searchTxtFld: CommonTextFieldSearch!
|
|
@IBOutlet private weak var height: NSLayoutConstraint!
|
|
|
|
private let completion: (Common.Model.Menu) -> Void
|
|
private let service: CommonMenuAutocompleteService
|
|
private var collection = [Common.Model.Menu]()
|
|
private var isLoading = false
|
|
private var selected: Common.Model.Menu?
|
|
|
|
init(
|
|
image: UIImage? = nil,
|
|
title: String? = nil,
|
|
text: String? = nil,
|
|
placeholder: String? = nil,
|
|
service: CommonMenuAutocompleteService,
|
|
selected: Common.Model.Menu? = nil,
|
|
_ completion: @escaping (Common.Model.Menu) -> Void
|
|
) {
|
|
self.service = service
|
|
self.selected = selected
|
|
self.completion = completion
|
|
super.init(nibName: "CommonControllerAutocomplete", bundle: nil)
|
|
self.title = title
|
|
self.text = text
|
|
self.image = image
|
|
_ = view
|
|
height.constant = 2*UIScreen.main.bounds.height/3
|
|
view.layoutIfNeeded()
|
|
searchTxtFld.lzPlaceholder = placeholder
|
|
tableView.register(cell: CommonCellAutocomplete.self)
|
|
service.didUpdate = {
|
|
Loader.hide(in: self.tableView)
|
|
self.collection = service.collection
|
|
self.isLoading = false
|
|
self.tableView.reloadData()
|
|
}
|
|
reload()
|
|
}
|
|
|
|
required init?(coder: NSCoder) {
|
|
fatalError("init(coder:) has not been implemented")
|
|
}
|
|
|
|
override func viewWillAppear(_ animated: Bool) {
|
|
super.viewWillAppear(animated)
|
|
searchTxtFld.becomeFirstResponder()
|
|
}
|
|
|
|
private func reload() {
|
|
isLoading = true
|
|
tableView.reloadData()
|
|
if !Loader.isLoading(in: tableView) {
|
|
Loader.show(in: tableView)
|
|
}
|
|
service.apply(filter: searchTxtFld.text)
|
|
}
|
|
|
|
}
|
|
|
|
extension CommonControllerAutocomplete: CommonTextFieldSearchDelegate {
|
|
func textFieldDidChange(_ textField: CommonTextFieldSearch) {
|
|
reload()
|
|
}
|
|
}
|
|
|
|
extension CommonControllerAutocomplete: UITableViewDataSource, UITableViewDelegate {
|
|
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { isLoading ? 0 : collection.count }
|
|
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
|
let cell = tableView.dequeueReusableCell(CommonCellAutocomplete.self, indexPath: indexPath)
|
|
cell.adjust(to: collection[indexPath.row], isSelected: selected == collection[indexPath.row])
|
|
return cell
|
|
}
|
|
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
|
|
selected = collection[indexPath.row]
|
|
tableView.reloadData()
|
|
dismiss(animated: true) { self.completion(self.collection[indexPath.row]) }
|
|
}
|
|
}
|