我正在嘗試為每個部分選擇一個單元格。一切正常,但是當我將 tableview 滾動到底部或頂部時,復選標記附件出現在隨機單元格上。這是代碼:
tableView.allowsMultipleSelection = true
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
// Find any selected row in this section
if let selectedIndexPath = tableView.indexPathsForSelectedRows?.first(where: { $0.section == indexPath.section}) {
// Deselect the row
tableView.deselectRow(at: selectedIndexPath, animated: false)
// deselectRow doesn't fire the delegate method so need to
// unset the checkmark here
tableView.cellForRow(at: selectedIndexPath)?.accessoryType = .none
}
return indexPath
}
func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
// Prevent deselection of a cell
return nil
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
任何幫助將不勝感激以避免這種情況
uj5u.com熱心網友回復:
發生這種情況是因為細胞是可重復使用的。我不認為這是一個好主意,通話tableView.cellForRow中didSelectRowAt。你必須控制其indexPath中選擇cellForRowAt
試試這個 :
var selectedRows = [IndexPath]() // selected indexPaths array
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if selectedRows.contains(indexPath){ // if already selected , remove
selectedRows = selectedRows.filter({$0 != indexPath})
}else{
selectedRows.append(indexPath)
}
tableView.reloadRows(at: [indexPath], with: .automatic)
}
在你的 cellForRowAt
if selectedRows.contains(indexPath){
cell.accessoryType = .checkmark
}else{
cell.accessoryType = .none
}
uj5u.com熱心網友回復:
發生這種情況是因為您正在對螢屏單元格進行更改,而沒有更新模型以反映這些更改。然后當一個單元格被回收時,有時你會拿起一個仍然有復選標記的單元格。
不要進入細胞并改變它們的外觀。相反,將單元格標記為需要更新(通過呼叫reloadRows(at:with)),然后在您的tableView(cellForRowAt:)方法中,始終將附件型別設定為.none或.checkmark。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/405068.html
標籤:
