Swift 选择可重用tableview单元格时索引超出范围
我有以下类来跟踪tableview中选择的所有单元格,问题是我一直在接收行上超出范围的错误索引:Swift 选择可重用tableview单元格时索引超出范围,swift,uitableview,Swift,Uitableview,我有以下类来跟踪tableview中选择的所有单元格,问题是我一直在接收行上超出范围的错误索引: self!.myModels[indexPath.row].isSelected ? self?.selectRow(indexPath) : self?.unselectRow(indexPath) 这是什么原因造成的?一旦加载tableView,问题就会出现 代码的其余部分: class CheckableTableViewCell: UITableViewCell { var han
self!.myModels[indexPath.row].isSelected ? self?.selectRow(indexPath) : self?.unselectRow(indexPath)
这是什么原因造成的?一旦加载tableView,问题就会出现
代码的其余部分:
class CheckableTableViewCell: UITableViewCell {
var handler: ((Bool)->())?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.accessoryType = selected ? .checkmark : .none
handler?(selected)
}
}
class TableViewController: UITableViewController {
private var myModels: [MyModel] = [MyModel(isSelected: false),MyModel(isSelected: true),MyModel(isSelected: true),MyModel(isSelected: false) ]
var sections = [Section]()
var structure = [Portfolios]()
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CheckableTableViewCell
cell.handler = {[weak self] selected in
self?.myModels[indexPath.row].isSelected = selected
}
let section = sections[indexPath.section]
let item = section.items[indexPath.row]
cell.textLabel?.textAlignment = .left
cell.selectionStyle = .none
let titleStr = "\(item.code)
cell.textLabel!.text = titleStr
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedIndexPath = indexPath.row
myModels[selectedIndexPath].isSelected = true
self.tableView.reloadRows(at: [indexPath], with: .none)
}
节定义了以下tableView结构:
struct Section {
let name : String
var items : [Portfolios]
}
struct Portfolios: Decodable {
let code: String
enum CodingKeys : String, CodingKey {
case code
}
}
我删除了我的答案,因为你的代码太混乱了
myModels
(保存所选信息的位置)与数据源完全不相关?你必须把<代码>选择< <代码> > <代码>投资组合(语义上实际上是代码>投资组合),并考虑代码< > DeDestRoTrw >中的部分。我真的很不喜欢这种方法,但我似乎无法掌握一个更好的方法来完成这一切。您将如何从头开始处理这个问题?正如我所说,isSelected
属于Portfolio
(不要将其包含在codingkey中)。实际上不需要回调,从模型中更新cellForRow
中单元格的isSelected
,并在didSelect
/didSelect
中更改它。另一个问题是,你真的需要改变颜色来表示选择,还是复选标记就足够了?看起来很相似。有一个解决办法。