У меня есть два представления коллекции (restaurantCollectionView и filterCollectionView), и я хочу обновить restaurantCollectionView после выбора ячейки filterCollectionView. Я пробовал использовать функцию didSelected
. Однако кажется, что функция всегда принимает в качестве входных данных restaurantCollectionView, а не filterCollectionView. Как я могу добиться фильтрации с помощью этих двух представлений коллекции?
Вот мой текущий код. Я не учел некоторые нерелевантные коды настройки, такие как создание объектов Restaurant и Filter.
class ViewController: UIViewController {
var filterCollectionView: UICollectionView!
var restaurantCollectionView: UICollectionView!
var filters = [Filter]()
var restaurants1 = [Restaurant]()
var restaurants2 = [Restaurant]()
override func viewDidLoad() {
super.viewDidLoad()
title = "My Restaurants"
view.backgroundColor = .lightGray
navigationController?.navigationBar.barTintColor = UIColor(displayP3Red: 0.2, green: 0.3, blue: 0.8, alpha: 0.7)
navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
filters = [mexican, american, asian, greek, fastfood, seafood, breakast, lunch, dinner, cheap, acceptable]
restaurants1 = [chipotle, chick, pokeland, ctb, fourseasons, aladdins]
restaurants2 = [chipotle, chick, pokeland, ctb, fourseasons, aladdins]
let filterLayout = UICollectionViewFlowLayout()
filterLayout.scrollDirection = .horizontal
filterLayout.minimumInteritemSpacing = padding
filterLayout.minimumLineSpacing = padding
let restaurantLayout = UICollectionViewFlowLayout()
restaurantLayout.scrollDirection = .vertical
restaurantLayout.minimumInteritemSpacing = 5
restaurantLayout.minimumLineSpacing = padding
filterCollectionView = UICollectionView(frame: .zero, collectionViewLayout: filterLayout)
filterCollectionView.translatesAutoresizingMaskIntoConstraints = false
filterCollectionView.backgroundColor = .lightGray
filterCollectionView.register(FilterCollectionViewCell.self, forCellWithReuseIdentifier: filterReuseIdentifier)
filterCollectionView.dataSource = self
filterCollectionView.delegate = self
view.addSubview(filterCollectionView)
restaurantCollectionView = UICollectionView(frame: .zero, collectionViewLayout: restaurantLayout)
restaurantCollectionView.translatesAutoresizingMaskIntoConstraints = false
restaurantCollectionView.backgroundColor = .lightGray
restaurantCollectionView.register(RestaurantCollectionViewCell.self, forCellWithReuseIdentifier: restaurantReuseIdentifier)
restaurantCollectionView.dataSource = self
restaurantCollectionView.delegate = self
view.addSubview(restaurantCollectionView)
setupConstraints()
}
func setupConstraints() {
NSLayoutConstraint.activate([
filterCollectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 2),
filterCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding),
filterCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding),
filterCollectionView.heightAnchor.constraint(equalToConstant: 70)
])
NSLayoutConstraint.activate([
restaurantCollectionView.topAnchor.constraint(equalTo: filterCollectionView.bottomAnchor, constant: 2),
restaurantCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
restaurantCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
restaurantCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10)
])
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.filterCollectionView{
return filters.count
}
else {
return restaurants2.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.filterCollectionView {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: filterReuseIdentifier, for: indexPath) as! FilterCollectionViewCell
cell.backgroundColor = .white
cell.filterName.setTitleColor(UIColor(displayP3Red: 0.2, green: 0.3, blue: 0.8, alpha: 0.7), for: .normal)
cell.configure(filter: filters[indexPath.item])
cell.filterName.addTarget(self, action: #selector(changeColor), for: .touchUpInside)
return cell
}
else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: restaurantReuseIdentifier, for: indexPath) as! RestaurantCollectionViewCell
cell.configure(restaurant: restaurants2[indexPath.item])
return cell
}
}
@objc func changeColor(sender: Any) {
if let button = sender as? UIButton {
let point: CGPoint = button.convert(.zero, to: filterCollectionView)
if let indexPath = filterCollectionView.indexPathForItem(at: point) {
let cell = filterCollectionView.cellForItem(at: indexPath) as! FilterCollectionViewCell
if cell.backgroundColor == UIColor.white{
cell.backgroundColor = UIColor(displayP3Red: 0.2, green: 0.3, blue: 0.8, alpha: 0.7)
cell.filterName.setTitleColor(.white, for: .normal)
}
else {
cell.backgroundColor = UIColor.white
cell.filterName.setTitleColor(UIColor(displayP3Red: 0.2, green: 0.3, blue: 0.8, alpha: 0.7), for: .normal)
}
}
}
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if collectionView == self.filterCollectionView{
return CGSize(width: 100, height: 50)
}
else {
let width = (collectionView.frame.width - 2 * padding) / 2.0
let height = (collectionView.frame.height - 3 * padding) / 4.0
return CGSize(width: width, height: height)
}
}
}
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == self.filterCollectionView {
let requirement = filters[indexPath.item].filterName
restaurants2 = restaurants1.filter({$0.cuisine.contains(requirement) || $0.time.contains(requirement) || $0.priceLevel == requirement})
restaurantCollectionView.reloadData()
}
}
}