我的 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)也被选中。我想根据部分单独选择行。
最佳答案
对于单节 TableView ,您可以使用 selectedIndexPath
来存储选定的 indexPath。对于多节 TableView ,您需要一个索引路径数组
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 方法中从数组中删除 seaved 索引路径
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
关于ios - 根据部分更改选定的单元格图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55589105/