如何清除TableView并重新加载数据?

时间:2018-05-28 11:43:38

标签: swift firebase firebase-realtime-database uicollectionview

我有这样的功能,当我用按钮重新加载时,这个函数collectionViewTable第二次显示相同的数据。我怎么解决?

func getWallpaperFromDB(){
        let databaseRef = Database.database().reference()
        databaseRef.child("wallpapers").observe(DataEventType.childAdded) { (snapshot) in
            if let value = snapshot.value! as? [String: Any] {
                let categoryID = value["categoryID"] as! String
                let categoryName = value["categoryName"] as! String
                let wallpaperName = value["wallpaperName"] as! String
                let wallpaperId = snapshot.key
                let DBWallpaper = Wallpaper(categoryID: categoryID, categoryName: categoryName, wallpaperId: wallpaperId, wallpaperName: wallpaperName)
                self.wallpapers.append(DBWallpaper)
                self.collectionViewTable.reloadData()
            }

        }
    }

@IBAction func slideMenuButton(_ sender: Any) {
        getWallpaperFromDB()
    }

2 个答案:

答案 0 :(得分:1)

您需要清除每次通话

@IBAction func slideMenuButton(_ sender: Any) {
    wallpapers.removeAll()
    getWallpaperFromDB()
}

答案 1 :(得分:1)

您可以在关闭函数中清空墙纸数组。这样,每次调用该函数时,wallets数组将为空,然后再次获取数据。这样,您就不会有重复的数据。

func getWallpaperFromDB(){

        let databaseRef = Database.database().reference()
        databaseRef.child("wallpapers").observe(DataEventType.childAdded) { (snapshot) in
            
            self.wallpapers = [] 
            
            if let value = snapshot.value! as? [String: Any] {
                let categoryID = value["categoryID"] as! String
                let categoryName = value["categoryName"] as! String
                let wallpaperName = value["wallpaperName"] as! String
                let wallpaperId = snapshot.key
                let DBWallpaper = Wallpaper(categoryID: categoryID, categoryName: categoryName, wallpaperId: wallpaperId, wallpaperName: wallpaperName)
                self.wallpapers.append(DBWallpaper)
                self.collectionViewTable.reloadData()
            }

        }
    }

@IBAction func slideMenuButton(_ sender: Any) {
        getWallpaperFromDB()
    }