UICollectionView не перезагружает результаты поиска даже с reloadData - PullRequest
1 голос
/ 16 февраля 2020

Я могу получить функцию поиска для фильтрации результатов, но она не будет отображать результаты поиска на эмуляторе iPhone. Он отображает результаты на iPhone у меня (iPhone 5), но не на эмуляторе. Я не знаю, почему их коллекция не обновляется, пока я печатаю. Элементы в массиве отображаются, потому что при первом переходе к этому экрану я вижу их.

my screenshot

import UIKit



class BrowseViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate {




    @IBOutlet weak var testCollectionView: UICollectionView!



    var Array = [Product]()
    var currentArray = [Product]() //update table





    private func setUpAnimals() {

        Array.append(Product(name: "Cheetos", price: "3.99", image:"1"))
        Array.append(Product(name: "Coca Cola", price: "2.29", image:"2"))
        Array.append(Product(name: "Red Bull", price: "3.79", image:"3"))
        Array.append(Product(name: "Doritos", price: "1.99", image:"4"))
        Array.append(Product(name: "Lays Barbecue", price: "1.89", image:"5"))
        Array.append(Product(name: "Skittles", price: "1.49", image:"6"))
        Array.append(Product(name: "Cheez It", price: "1.29", image:"7"))
        Array.append(Product(name: "Pringles", price: "3.49", image:"8"))
        Array.append(Product(name: "Lays", price: "1.89", image:"9"))
        Array.append(Product(name: "Fritos", price: "3.99", image:"10"))


        currentArray = Array

    }



    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setUpAnimals()
        self.view.backgroundColor = UIColor.white
        let itemSize = UIScreen.main.bounds.width/3 - 3

        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets.init(top: 30, left: 0, bottom: 20, right: 0)
        layout.itemSize = CGSize (width: itemSize, height: itemSize)

        layout.minimumInteritemSpacing = 3
        layout.minimumLineSpacing = 3

        testCollectionView.collectionViewLayout = layout



    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }








    // Number of views in the collection view

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.currentArray.count
    }



    //Populating the viewsc

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // Shows Image
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! TestCollectionViewCell
        cell.testImageView.image = UIImage(named: currentArray[indexPath.row].image + ".jpg")
        cell.titleLabel.text = (self.currentArray[indexPath.row].name)
        cell.priceLabel.text = ("$" + self.currentArray[indexPath.row].price)

        return cell
    }






    // Search Bar
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        currentArray = Array.filter({ Product -> Bool in
            switch searchBar.selectedScopeButtonIndex {
            case 0:
                if searchText.isEmpty { return true }
                return Product.name.lowercased().contains(searchText.lowercased())
            default:
                return false
            }
        })
        //self.testCollectionView.reloadData()
       DispatchQueue.main.async { [weak self] in
            self?.testCollectionView.reloadData()
        }


    }

    func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
        switch selectedScope {
        case 0:
            currentArray = Array

        default:
            break
        }
           DispatchQueue.main.async { [weak self] in
                     self?.testCollectionView.reloadData()
                 }

    }


    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let VC = storyboard?.instantiateViewController(withIdentifier: "AddToCartViewController") as? AddToCartViewController
        VC?.image = UIImage(named: currentArray[indexPath.row].image + ".jpg")!
        VC?.name = (self.currentArray[indexPath.row].name)
        VC?.price = (self.currentArray[indexPath.row].price)
        self.navigationController?.pushViewController(VC!, animated: true)

    }



}

1 Ответ

2 голосов
/ 16 февраля 2020

Проблема в том, что вы не установили делегата, поэтому методы обратного вызова панели поиска не вызываются!

Если вы используете SearchController, вам нужно добавить эту строку в viewDidLoad

navigationItem.searchController?.searchBar.delegate = self

В противном случае установите для него делегат searchBar

searchBar.delegate = self

Примечание. Вам следует изменить имя Array на более описательное имя в соответствии с соглашением об именовании в случае с верблюдом, например filteredArray

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