我的tableView
中有3个部分,我希望每个部分都像单选按钮那样进行单选。我的代码适用于单个部分,但不适用于多个部分。我没有为此使用任何自定义按钮,而是直接使用contentView
imageView
设置图像并使用didSelectRowAt indexPath:
进行选择
我的代码是
cell?.imageView?.image = UIImage.init(named: "radio1")//Deselected state
cell?.imageView?.tag = indexPath.row
cell?.contentView.viewWithTag(8888)
if (selectedIndexPath != nil && selectedIndexPath?.section == 0 && selectedIndexPath?.row == indexPath.row) {
cell?.imageView?.image = UIImage.init(named: "radio2")//Selected state
} else {
cell?.imageView?.image = UIImage.init(named: "radio1")//Deselected state
}
if selectedIndexPath?.section == 1 {
}
if selectedIndexPath?.section == 2 {
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndexPath = indexPath//Save selected indexpath
print(selectedIndexPath)
tblView.reloadData()
上面的代码得到类似的结果
当我自动选择(Section1,Row0)时(Section2,Row0)也被选择。我想根据部分分别选择行。
答案 0 :(得分:2)
对于单节表视图,您可以使用selectedIndexPath
存储选定的indexPath。对于多节表视图,您需要一个indexPaths数组
var selectedIndexPathArr: [IndexPath?] = Array(repeating: nil, count: 3)//3 is number of sections
然后在didSelect方法中将选定的索引路径存储在其部分索引中
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndexPathArr[indexPath.section] = indexPath//save selected indexpath depends section
tableView.reloadData()
}
在didDeselectRowAt方法中,从数组中删除缝制的索引路径
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
selectedIndexPathArr[indexPath.section] = nil//delete selected indexpath depends section
tableView.reloadData()
}
在cellForRowAt方法中,将当前索引路径与数组中的索引路径进行比较,取决于当前部分
if selectedIndexPathArr[indexPath.section] == indexPath {
cell?.imageView?.image = UIImage.init(named: "radio2")//Selected state
} else {
cell?.imageView?.image = UIImage.init(named: "radio1")//Deselected state
}
然后您可以获取每个部分的选定索引路径
如果在特定部分中未选择任何单元格,则会得到nil
print(selectedIndexPathArr[0])//first section selected indexpath
print(selectedIndexPathArr[1])//second section selected indexpath
print(selectedIndexPathArr[2])//third section selected indexpath