metatext/View Controllers/ExploreViewController.swift

71 lines
2.6 KiB
Swift
Raw Normal View History

2021-01-23 03:48:33 +00:00
// Copyright © 2021 Metabolist. All rights reserved.
2021-01-25 07:42:39 +00:00
import Combine
2021-01-23 03:48:33 +00:00
import UIKit
import ViewModels
final class ExploreViewController: UICollectionViewController {
private let viewModel: ExploreViewModel
private let rootViewModel: RootViewModel
2021-01-25 07:42:39 +00:00
private var cancellables = Set<AnyCancellable>()
2021-01-23 03:48:33 +00:00
init(viewModel: ExploreViewModel, rootViewModel: RootViewModel) {
2021-01-23 03:48:33 +00:00
self.viewModel = viewModel
self.rootViewModel = rootViewModel
super.init(collectionViewLayout: UICollectionViewFlowLayout())
tabBarItem = UITabBarItem(
title: NSLocalizedString("main-navigation.explore", comment: ""),
image: UIImage(systemName: "magnifyingglass"),
selectedImage: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("main-navigation.explore", comment: "")
2021-01-25 02:10:41 +00:00
let searchResultsController = TableViewController(
viewModel: viewModel.searchViewModel,
rootViewModel: rootViewModel,
insetBottom: false,
parentNavigationController: navigationController)
2021-01-23 03:48:33 +00:00
2021-01-25 02:10:41 +00:00
let searchController = UISearchController(searchResultsController: searchResultsController)
2021-01-25 07:42:39 +00:00
searchController.searchBar.scopeButtonTitles = SearchScope.allCases.map(\.title)
2021-01-23 03:48:33 +00:00
searchController.searchResultsUpdater = self
navigationItem.searchController = searchController
2021-01-25 07:42:39 +00:00
viewModel.searchViewModel.events.sink { [weak self] in
if case let .navigation(navigation) = $0,
case let .searchScope(scope) = navigation {
searchController.searchBar.selectedScopeButtonIndex = scope.rawValue
self?.updateSearchResults(for: searchController)
}
}
.store(in: &cancellables)
2021-01-23 03:48:33 +00:00
}
}
extension ExploreViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
2021-01-25 07:42:39 +00:00
if let scope = SearchScope(rawValue: searchController.searchBar.selectedScopeButtonIndex) {
if scope != viewModel.searchViewModel.scope,
let scrollView = searchController.searchResultsController?.view as? UIScrollView {
scrollView.setContentOffset(.init(x: 0, y: -scrollView.safeAreaInsets.top), animated: false)
}
2021-01-25 02:10:41 +00:00
viewModel.searchViewModel.scope = scope
}
2021-01-23 03:48:33 +00:00
viewModel.searchViewModel.query = searchController.searchBar.text ?? ""
}
}