数组中的所有项目不在UITableView中

时间:2018-12-10 19:49:22

标签: swift firebase oop

下面是CatalogViewController,其中包含一个表格视图。表格视图有1个原型单元ShopCell。当我在循环中打印项目时,它们打印正确,但是在表中显示时,项目丢失。 (删除shuffle()方法不会执行任何操作,而删除removeDuplicates()会导致项目出现多次)。我没有包括addToFavorites(cell:ShopCell),因为我正在对其进行测试。它什么都不做。

protocol ShopCellDelegate {
    func addToFavorites(cell: ShopCell)

}

class ShopCell: UITableViewCell {

    @IBOutlet weak var productImageView: UIImageView!

    @IBOutlet weak var titleLabel: UILabel!

    @IBOutlet weak var priceLabel: UILabel!

    @IBOutlet weak var descTV: UITextView!

    @IBOutlet weak var favoriteButton: UIButton!

    var delegate: ShopCellDelegate?


    override func prepareForReuse() {
       super.prepareForReuse()

        self.productImageView.image = nil
        self.titleLabel.text = ""
        self.priceLabel.text = ""
        self.descTV.text = ""
        self.favoriteButton.isHidden = true

    }

    func setProduct(product: Product) {
        productImageView.sd_setImage(with: URL(string: product.urlToImage!), placeholderImage: UIImage(named: "1024ELP.png"))
        titleLabel.text = product.itemName!
        priceLabel.text = product.priceTag!
        descTV.text = product.itemDesc!
    }


    @IBAction func favOrUnfav(_ sender: UIButton) {
        if let delegate = self.delegate {
            delegate.addToFavorites(cell: self)
        }

    }

}

//

class CatelogViewController: UIViewController, GADInterstitialDelegate, SFSafariViewControllerDelegate, UITableViewDelegate, UITableViewDataSource, ShopCellDelegate {


    @IBOutlet weak var tableView: UITableView!


    static var shopType = String()
    static var linkToVisit = String()

    var myProducts = [Product]()
    var productKeys = [String]()

    var interstitial: GADInterstitial!


    override func viewWillAppear(_ animated: Bool) {

       visuals() // Sets Nav Bar color & changes cell size if device == ipad

    }


    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.navigationController?.navigationBar.tintColor = UIColor.black
        if CatelogViewController.shopType == "Apparel" {
            self.title = NSLocalizedString("Shop Apparel", comment: "")
            fetchProductLinks(child1: "ProductList", child2: "Products")

        }else{
            self.title = NSLocalizedString("Shop Others", comment: "")
            fetchProductLinks(child1: "OtherList", child2: "OtherProducts")
            //shuffleItems()
        }
        if let index = self.tableView.indexPathForSelectedRow{
            self.tableView.deselectRow(at: index, animated: true)
        }



    }


    // MARK: - Table view data source

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myProducts.count
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ShopCell
        let product = myProducts[indexPath.row]
        cell.delegate = self
        cell.favoriteButton.isHidden = true
        cell.setProduct(product: product)

        return cell
    }


    func fetchProductLinks(child1: String, child2: String) {

        let ref = Database.database().reference()
        let prodRef = ref.child(child1).child(child2)
        prodRef.observeSingleEvent(of: .value, with: { snapshot in

            self.myProducts.removeAll()

            for items in snapshot.children {
                let item = items as! DataSnapshot
                let product = item.value as! [String : String]
                let name = product["Name"]
                let link = product["Link"]
                let img = product["urlToImage"]
                let desc = product["Description"]
                let price = product["Price"]
                let newProduct = Product(urlToImage: img, itemName: name, itemLink: link, itemDesc: desc, priceTag: price)
                self.myProducts.append(newProduct)
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }

            }


            self.myProducts = self.shuffleArray(array: self.myProducts) as! [Product]
            self.myProducts = self.myProducts.removeDuplicates()



        })

        ref.removeAllObservers()


    }

extension Array where Element:Equatable {
func removeDuplicates() -> [Element] {
    var result = [Element]()

    for value in self {
        if result.contains(value) == false {
            result.append(value)
        }
    }

    return result
}

}

1 个答案:

答案 0 :(得分:0)

您可以对数组进行混洗,并删除重复的数组,但是不会在数组之后重新加载数据。因此,重新加载表格视图的数据

self.myProducts = self.shuffleArray(array: self.myProducts) as! [Product]
self.myProducts = self.myProducts.removeDuplicates()
self.tableView.reloadData()