我有一个问题,每当重新加载tableView时,都会重复相同的单元格。
有什么可以阻止这种情况的吗?我尝试搜索,但不幸的是没有找到解决方法的运气,所以我决定在此处发布。我是新手,所以如果我想念什么,请告诉我。
这是我的代码:
var list:[String] = []
class Services: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var videos: [String] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = list[indexPath.row]
return(cell)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 172
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondVC = storyboard.instantiateViewController(identifier: "ChangeTitle") as! Services
self.navigationController?.pushViewController(secondVC, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// print(scoreLabelA.text!)
arrayOfCellData = [cellData(cell: 1, text: "Meow")]
tableView?.reloadData()
handle = ref.child("ServiceA").observe(.childAdded, with: { DataSnapshot in
if let item = DataSnapshot.value as? String {
list.append(item)
self.tableView?.reloadData()
}
})
tableView.backgroundColor = .clear
tableView?.delegate = self
tableView?.dataSource = self
}
}
有什么办法可以解决?提前谢谢了。 :)
因为var list:[String] = []
在您的Services
类之外,所以它一直存在。在执行以下操作以重新填充属性之前,要么将其移动到类中,要么将其清空:
override func viewDidLoad() {
super.viewDidLoad()
arrayOfCellData = [cellData(cell: 1, text: "Meow")]
tableView?.reloadData()
//Add this:
list = []
handle = ref.child("ServiceA").observe(.childAdded, with: { DataSnapshot in
if let item = DataSnapshot.value as? String {
list.append(item)
self.tableView?.reloadData()
}
})