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

标签 swift firebase oop

下面是 CatalogViewController,它包含一个 TableView 。 tableview 有 1 个原型(prototype)单元,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
}

}

最佳答案

您对数组进行洗牌并删除重复项,但不会在其之后重新加载数据。因此重新加载 TableView 的数据

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

关于swift - 数组中不在 UITableView 中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53712621/

相关文章:

swift - 执行 segue 丢失导航 Controller

ios - Swift - xib 中不需要的边距

ios - 如何在没有边界的情况下使两个按钮中心 View 位于中心?

android - 如何在不监听事件的情况下从firebase数据库检索数据

android - 为什么 Firebase 可以在没有互联网许可的情况下在我的应用程序上运行

Firebase 匿名身份验证

python - 派生类无法识别父类方法的参数

regex - 快速替换出现的正则表达式

java - 如何以OO方式修改返回值设计?

php - 我可以将代码包含到 PHP 类中吗?