我有一个带有自定义单元格的表格 View ,数据来自 Realm :
var Materials: Results<RealmMaterial>!
override func viewDidLoad() {
let realm = RealmService.shared.realm
Materials = realm.objects(RealmMaterial.self).filter("InspectResult == 0")
}
在每个单元格中,我都有一些按钮,其属性随单元格信息而变化。我这样处理:
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "MaterialCell") as! MaterialsTableViewCell
let myMaterial = Materials[indexPath.row]
cell.materialCodeLbl.text = myMaterial.Number
cell.materialDescLbl.text = myMaterial.Desc
cell.redBtnOutlet.tag = myMaterial.Id
cell.greenBtnOutlet.tag = myMaterial.Id
cell.yellowBtnOutlet.tag = myMaterial.Id
cell.cellView.layer.shadowColor = UIColor.black.cgColor
cell.cellView.layer.shadowOpacity = 0.1
cell.cellView.layer.shadowOffset = CGSize.zero
cell.cellView.layer.shadowRadius = 10
cell.cellView.layer.cornerRadius = 10
cell.redBtnOutlet.layer.cornerRadius = 5
cell.greenBtnOutlet.layer.cornerRadius = 5
cell.yellowBtnOutlet.layer.cornerRadius = 5
if myMaterial.InspectResult == 1 {
cell.greenBtnOutlet.backgroundColor = UIColor(red: 137/255, green: 206/255, blue: 75/255, alpha: 1)
cell.yellowBtnOutlet.backgroundColor = UIColor(red: 192/255, green: 192/255, blue: 192/255, alpha: 1)
cell.redBtnOutlet.backgroundColor = UIColor(red: 192/255, green: 192/255, blue: 192/255, alpha: 1)
}
else if myMaterial.InspectResult == 2 {
cell.redBtnOutlet.backgroundColor = UIColor(red: 253/255, green: 77/255, blue: 67/255, alpha: 1)
cell.greenBtnOutlet.backgroundColor = UIColor(red: 192/255, green: 192/255, blue: 192/255, alpha: 1)
cell.yellowBtnOutlet.backgroundColor = UIColor(red: 192/255, green: 192/255, blue: 192/255, alpha: 1)
}
else if myMaterial.InspectResult == 3 {
cell.yellowBtnOutlet.backgroundColor = UIColor(red: 240/255, green: 192/255, blue: 16/255, alpha: 1)
cell.greenBtnOutlet.backgroundColor = UIColor(red: 192/255, green: 192/255, blue: 192/255, alpha: 1)
cell.redBtnOutlet.backgroundColor = UIColor(red: 192/255, green: 192/255, blue: 192/255, alpha: 1)
}
return cell
}
但是当我重新加载数据单元格的对象属性不会改变。看起来cellForRowAt
不会再次执行,并且属性来自单元格的索引。
第一次加载数据时,它工作正常。但是当我重新加载数据时,新数据不会再次改变
最佳答案
在我看来,您正在重新加载表格 View ,但实际上并未更新数据。
摘自您的陈述
It seams that cellForRowAt dose not execute again
我想您尚未真正确认 cellForRowAt
未执行,我的猜测是它正在执行,但 Materials
数组尚未更新您的新数据。
在调用 tableView.reloadData()
之前,确保 Materials
具有新数据。
关于swift - 当我调用 reload tableView.reloadData() 时,自定义单元格属性不会更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50770877/