Реализуйте фильтры кнопок для UICollectionView - PullRequest
0 голосов
/ 08 ноября 2019

Я бы хотел реализовать фильтры для CollectionView, чтобы при нажатии на них CollectionView обновлялся, отображая только тот тип одежды, который я ищу (одежда будет отфильтрована по атрибуту, который они назвали "категория "(джинсы, рубашки и т. д.). Моя последняя цель показана в этом макете: Цель

Это то, что у меня есть в настоящее время (пустое пространство вверху - заголовок или"Коллекция многоразового просмотра ": Текущая работа

Это мой viewController:

import UIKit
import Firebase
import FirebaseAuth
import FirebaseFirestore
import SDWebImage

class CategoriesViewController: UICollectionViewController {

    @IBOutlet var ClothesCollectionView: UICollectionView!


    //Firestore setup constants
    var db: Firestore!
    let uid = String(Auth.auth().currentUser!.uid);

    //Images setup
    var clothes = [Clothes]()
    var customImageFlowLayout: CustomImageFlowLayout!
    var headerView: CategoriesHeaderView?
    var favoriteClothes: [String] = []

    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()
        loadFavList()
        loadImagesDB ()
        // Do any additional setup after loading the view
        customImageFlowLayout = CustomImageFlowLayout()
        ClothesCollectionView.collectionViewLayout = customImageFlowLayout
        ClothesCollectionView.register(CategoriesHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "CartHeaderCollectionReusableView2")

    }

    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        headerView = ClothesCollectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "CartHeaderCollectionReusableView2", for: indexPath) as? CategoriesHeaderView
        return headerView!
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return .init(width: view.frame.width, height: 50)
    }

    func loadImagesDB (){

        let clothingReference = Firestore.firestore().collection("clothing")
        var newDataClothes = [Clothes]()

        clothingReference.addSnapshotListener { (snapshot, _) in
            Firestore.firestore().collection("users")
                .whereField("uid", isEqualTo: self.uid)
            .getDocuments() { (querySnapshot, err) in
                if let err = err {
                    // Some error occured
                    print("Error getting user data", err)
                } else {
                    guard (querySnapshot?.documents.first) != nil else {
                    print("Error")
                   return
                 }
                    guard let snapshot = snapshot else {return}
                    for document in snapshot.documents{
                        let myData = document.data()
                        let url = myData["src"] as? String
                        let name = myData["name"] as? String
                        let price = myData["price"] as! Int
                        let sizes = myData["sizes"] as! String
                        let category = myData["category"] as? String

                        let clothesData = Clothes(url: url!, id: "", name: name!, price: price, sizes: sizes, tags: "", category: category!, stores: [])

                        newDataClothes.append(clothesData)
                    }
                    self.clothes = newDataClothes
                    self.ClothesCollectionView.reloadData()
                }
            }
        }
    }

    func loadFavList(){
        let uid = String(Auth.auth().currentUser!.uid);
        let dbf = Firestore.firestore()

        dbf.collection("users")
        .whereField("uid", isEqualTo: uid)
        .getDocuments() { (querySnapshot, err) in
            if let err = err {
                // Some error occured
                print("Error getting user data", err)
            } else {
             guard let document = querySnapshot?.documents.first else {
               print("Error")
               return
             }
                self.favoriteClothes = document.get("favorites") as! [String]

            }
        }
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return clothes.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = ClothesCollectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ClotheCollectionViewCell

        let clothe = clothes[indexPath.row]

        cell.ClotheImage.sd_setImage(with: URL(string: clothe.url!), placeholderImage: UIImage(named: "image1"))

        if favoriteClothes.contains(clothe.name!) {
            cell.FavoriteButton.backgroundColor = UIColor.black
            cell.isFav = true
        } else {
            cell.isFav = false
        }

        cell.TitleLabel.text = clothe.name
        cell.PriceLabel.text = "Price: \(clothe.price ?? 0)"

        cell.layer.borderColor = UIColor.lightGray.cgColor
        cell.layer.borderWidth = 0.5

        let tap =  UITapGestureRecognizer(target: self, action: #selector(self.TappedCell(sender:)))

        tap.name = "\(indexPath.row)"

        cell.addGestureRecognizer(tap)



        return cell
    }

    @objc func TappedCell(sender: UITapGestureRecognizer ) {

        let clothe = clothes[Int(sender.name!)!]

        let clotheDetailViewController = self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.ClotheDetailViewController) as? ClotheDetailViewController

           clotheDetailViewController!.clothes = clothe
           clotheDetailViewController?.controller = "CategoriesVC"
           self.view.window?.rootViewController = clotheDetailViewController
           self.view.window?.makeKeyAndVisible()
    }

}

Мой CategoriesViewHeader действительно ничего не имеет:

import UIKit

class CategoriesHeaderView: UICollectionReusableView {

    override init(frame: CGRect) {
        super.init(frame: frame)

    }



    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

Все данные извлекаются из базы данных Firestore.

Если я через Main.Storyboard пытаюсь поместить кнопку в заголовок, она не появляется, когда я запускаю приложение. Я действительно оченьпотерянный здесь, я не знаю, что делать вообще.

Любые предложения о том, с чего мне начать? Буду признателен за любую помощь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...