【发布时间】:2018-02-13 14:21:39
【问题描述】:
我有一个多选的表格视图。
我在做什么:当用户选择项目时,这些项目会附加到数组中。
当用户从单元格中取消选择项目时,这个取消选择的项目从数组中删除。
我做了什么:
我的数组:var selectedTagList:[Tag] = []
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tagTableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
self.selectedTagList.append(tagList![indexPath.row])
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
self.tagTableView.cellForRow(at: indexPath)?.accessoryType = .none
self.selectedTagList.remove(at: indexPath.row)
}
请提供任何建议或示例代码?
//数据源和委托
extension PickVideoViewController : UITableViewDataSource,UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let tlist = self.tagList , !tlist.isEmpty else { return 1}
return tlist.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let tlist = self.tagList , !tlist.isEmpty else {
let cell = UITableViewCell()
cell.selectionStyle = .none
cell.backgroundColor = .clear
cell.textLabel?.textAlignment = .center
cell.textLabel?.textColor = UIColor.black
cell.textLabel?.text = "nodataavaiable".localized()
return cell }
let cell = tableView.dequeueReusableCell(withIdentifier: "TagCell", for: indexPath) as! TagCell
cell.tagName.text = tlist[indexPath.row].tag
cell.accessoryType = cell.isSelected ? .checkmark : .none
cell.selectionStyle = .none // to prevent cells from being "highlighted"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tagTableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
self.selectedTagList.append(tagList![indexPath.row])
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
self.tagTableView.cellForRow(at: indexPath)?.accessoryType = .none
self.selectedTagList.remove(at: <#T##Int#>)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let tlist = self.tagList , !tlist.isEmpty else {return tableView.frame.height }
return 40
}
}
【问题讨论】:
-
那么问题是什么?
-
问题是当 ı remove : out of bounds
-
你能展示你的 UITableViewDataSource 吗?
-
如果您选择第 10 个单元格,这是您的第二个选择。该数组将仅包含 2 个项目。您正试图在索引 9 处删除。这是超出范围的。
-
如果将数字 7 和数字 9 插入到数组中,它将有两个项目。然后您尝试删除第 7 项。看到这里的问题了吗?
标签: swift uitableview swift4