【发布时间】:2018-10-30 09:23:12
【问题描述】:
我专门管理的 tableView 有问题,我需要经常删除和添加行。我的单元是编程设计的。我更新了依赖于我的单元格并调用 self.tableView.reloadData() 的数组,但这不会删除我需要的单元格并像我的数组一样更新 tableView。
由于重用和我的单元格设计(以编程方式),我需要检查单元格是否始终是设计的。问题来自这里。
当我调用tableView.reloadData()时,我的数据没有正确重新加载,所以我需要删除单元格中的所有视图:表示单元格不是设计的,要设计新的单元格...当然我可以更新可见单元格(带有tableView.visibleCells),所以这个工作但我怎样才能更新我的其他不可见单元格?
也许我有架构问题?如果是这样,在定义了 indexPath 的 TableView 中删除和插入行的最佳方法是什么?或者,如何以编程方式只设计一次单元格?
代码:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return user.lobbySurvey.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"Celll") as! CardCell
for survey in user.lobbySurvey{
let index = user.lobbySurvey.index(where: {
//get the current index is nedeed else the cells reuse lazy
$0 === survey
})
if indexPath.row == index{
var surveyState : UserSurvey.state
surveyState = survey.state
switch surveyState{
case .selectSurvey:
cell.drawCard(statutOfCard: .selectSurvey)
case .goSurvey:
cell.drawCard(statutOfCard: .goSurvey(picture: survey.picture))
case .surveyEnded:
print("survey Ended")
case .surveyWork:
print("survey in progress to vote")
case .surveyWaiting:
cell.drawCard(statutOfCard: .surveyWaiting(selfSurveyId: survey.id, timeLeft: survey.timeLeft, picture: survey.picture))
case .buyStack:
cell.drawCard(statutOfCard: .buyStack(supView : self.view))
}
}
}
cell.delegate = self
cell.delegateCard = self
cell.layer.backgroundColor = UIColor.clear.cgColor
cell.backgroundColor = .clear
tableView.backgroundColor = .clear
tableView.layer.backgroundColor = UIColor.clear.cgColor
return cell
}
【问题讨论】:
-
“如何更新其他不可见的单元格?” 你不需要。只需更新您的数据源,这将在单元格可见后反映更改。
-
你能分享你负责在tableview中重新加载数据和更新数组中数据的代码
-
您是否覆盖了单元格中的 prepareForReuse() 以重置单元格的视图?请发布相关部分的代码 sn-ps,例如 numberOfRowsInSection 和 cellForRowAt。
-
@RakeshaShastri 是的,但是当我更新我的数据源时,具有旧相同行索引的旧单元格的设计保留在这里
-
如果整个数组发生了变化,您应该只调用
reloadData。如果您更改了特定行,请致电reloadRows,然后您的cellForRowAt可以负责更新单元格。不在屏幕上的单元格将被忽略,直到它们出现
标签: ios swift uitableview