ios - 根据部分更改选定的单元格图像

标签 ios swift uitableview

我的 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
}

enter image description here

然后你可以为每个部分获取选定的索引路径

如果在特定部分没有选择单元格,您将得到 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/

相关文章:

ios - Swift 协议(protocol)和扩展,我需要根据需要调用覆盖方法或默认扩展方法

ios - 试图弹出一个不存在的 View Controller

ios - 如何将 UISwitch 嵌入到静态 UITableView 中?

iphone - 尝试由不同的类加载时 TableView 崩溃

ios - 在 UICollectionViewCell 上双击手势?

ios - 使 TextView 的一半文本颜色不同于其他 50% 的文本 SWIFT

ios - 处理 Podfile 的安装后 Hook 时出错

Swift-使用完成处理程序更新闭包外部的全局变量

ios - 在循环执行期间更改 UIImageView UIImage

ios - 如何在 UITableView 的编辑模式下启用滑动删除和删除按钮