【发布时间】:2019-04-05 11:00:19
【问题描述】:
我在 tableview 中添加多项选择,并在 tableview 中添加部分,所以当用户单击特定部分内的单元格时,我如何存储该部分索引以及该单元格的索引路径以显示将作为选定项存储在数组中的单元格和在 cellForRowAtindexpath 中反映更好的解决方案是值得赞赏的
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemsInSections[section].count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.sections.count;
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = UIColor(red: 8/255, green: 38/255, blue: 76/255, alpha: 1.0)
header.backgroundColor = UIColor.clear
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tablheaders.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath)
let section = indexPath.section
if checkdarray.count > 0
{
if (self.checkdarray[section][indexPath.row] as Int == 1)
{
cell.accessoryType = .checkmark;
}
else
{
cell.accessoryType = .none;
}
}
cell.textLabel?.text = itemsInSections[indexPath.section][indexPath.row] as! String
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let section = indexPath.section as Int
let indepaths = indexPath.row as Int
tableView.cellForRow(at: indexPath as IndexPath)?.accessoryType = .checkmark
checkdarray.insert([1], at: [section][indepaths])
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath as IndexPath)?.accessoryType = .none
// checkdarray.remove(at: indexPath.row)
//checkdarray.insert(0, at: indexPath.row)
}
【问题讨论】:
-
我会使用
Set<IndexPath>,然后根据需要插入/删除索引路径。然后你在cellForRow(at:)中使用contains -
您的意思是仅使用 indexpath 将所选项目存储在数组中并进入 cellForRow(at:) 将该数组项目与 indexpath.row @Dávid Pásztor
-
不要存储在数组中,存储在
Set -
你有什么例子可以快速理解吗? @Paulw11
-
@Paulw11 为什么 Set 优于 Array?
标签: ios swift uitableview swift4 xcode10