我有一個tableview,並在每個單元格中有一個複選框。我也有一個「全選」按鈕。迭代通過TableViewCells跳過一些
我的問題是,當我點擊選擇所有我想更新所有複選框到選中狀態。所以從100個單元的列表中,全部被檢查,但每13個單元都沒有。爲了使它更清晰,在我的模擬器屏幕上顯示12個單元格,所有單元格都被檢查。當我開始滾動時,出現的第一個單元格被取消選中,然後是12個選中的單元格:S 當我滾動一下並再次單擊「全選」時,跳過的單元格也會被選中..
任何人都有線索我錯過了什麼?
這是單元代碼:
class ListTableViewCell: UITableViewCell {
@IBOutlet weak var checkbox: UIButton!
var buttonState = false{
didSet{
if buttonState{
checkbox.setImage(#imageLiteral(resourceName: "checked"), for: .normal)
}else{
checkbox.setImage(#imageLiteral(resourceName: "unchecked"), for: .normal)
}
}
}
@IBAction func checkboxAction(_ sender: UIButton) {
if buttonState {
buttonState = false
}else{
buttonState = true
}
}
func simulateCheck(){
buttonState = true
}
這裏是從我的控制器一些snipets:
private var articleValues: [ArticleValue] = []{
didSet{
tableView.reloadData()
}
}
func selectAll(){
for i in 0..<articleValues.count{
let cell = tableView.cellForRow(at: IndexPath(item: i, section: 0)) as? ListTableViewCell
cell?.simulateCheck()
tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "articleValueItem", for: indexPath)
// Cell Configuration
let articleValue = articleValues[indexPath.row]
if let articleValueCell = cell as? ListTableViewCell{
articleValueCell.articleValue = articleValue
}
return cell
}
爲什麼不在'articleValues'數組中創建一個屬性來檢查該項目以及何時重新載入數據(如果在「cellForRowAt」中選中)。不建議直接與單元交互,而是使用數據源。 – GIJOW
我想在你的selectAll()函數中,我會在這個函數的最後調用reloadData()。另外,爲什麼不在'cellForRowAt'函數中返回'articleValueCell'? – antonio081014
GIJOW大聲思考,articleValues連接到數據庫,並且我認爲將複選框狀態保存到數據庫不是一個好主意。也許雖然元組或字典可以做到這一點? antonio081014你的第一點是完全正確的性能問題,我想,但我不認爲這是問題。你的第二點......我不知道爲什麼!感謝您指出。 – Thodoris