gpt4 book ai didi

swift - 如何在每次再次加载 View 时清除 tableView 数据和 reloadData

转载 作者:行者123 更新时间:2023-11-28 13:33:40 25 4
gpt4 key购买 nike

我正在从 firebase 实时数据库中获取数据到我的 tableView 中,单击时单元格将使用来自 firebase 的 tableView 中的数据打开一个新 View ,但我需要 tableView 来监听 firebase 数据的变化,所以我做了一个监听器,但每次我关闭并重新打开 View Controller 时,tableView 不会 reloadData() 它只是将新数据添加到 tableView 中的数组而不删除旧数组数据,这使得每次我关闭并重新打开 View 时列表加倍 Controller

我可以使用什么代码来删除旧的 tableView 数据并将新的数据重新加载到其中,它的长度将相同,如果不是,它就像更新一样

override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self

dataService()

searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search NightClubs"

navigationItem.searchController = searchController
definesPresentationContext = true

searchController.searchBar.scopeButtonTitles = ["All", "Barrie", "Toronto", "London"]
searchController.searchBar.delegate = self
tableView.tableFooterView = searchFooter
}

override func viewWillAppear(_ animated: Bool) {
if let selectionIndexPath = self.tableView.indexPathForSelectedRow {
self.tableView.deselectRow(at: selectionIndexPath, animated: animated)
}
super.viewWillAppear(animated)
}

func dataService() {
DataService.ds.REF_BARS.observe(.value, with: { (snapshot) in
print(snapshot.value as Any)
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {
print(snap)
if let barData = snap.value as? Dictionary<String, AnyObject> {
let bar = NightClubs(barData: barData)
self.nightClubs.append(bar)
print(self.nightClubs)
self.tableView.reloadData()
}
self.tableView.reloadData()
}
self.tableView.reloadData()
self.smallerNightClubs = self.nightClubs//.filter { $0.promoted == "Yes"}
}
self.tableView.reloadData()
})
}

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

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering() {
searchFooter.setIsFilteringToShow(filteredItemCount: filteredNightClubs.count, of: smallerNightClubs.count)
return filteredNightClubs.count
}
searchFooter.setNotFiltering()
return nightClubs.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell") as! searchCell
let nightClub: NightClubs
if isFiltering() {
nightClub = filteredNightClubs[indexPath.row]
} else {
nightClub = nightClubs[indexPath.row]
}
cell.locationTextLabel.text = nightClub.location
cell.nameTextLabel.text = nightClub.name
return cell
}

最佳答案

你需要在下一次追加之前清除数组

self.nightClubs.removeAll()
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {

关于swift - 如何在每次再次加载 View 时清除 tableView 数据和 reloadData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56979912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com