【问题标题】:Change selected cell image based on sections根据部分更改选定的单元格图像
【发布时间】:2019-04-09 18:58:33
【问题描述】:

我的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)也被选中。我想根据部分单独选择行。

【问题讨论】:

  • 你为什么不使用带状态的按钮?我对你的问题非常不清楚。
  • 你能告诉这个你是怎么创建这个的吗selectedIndexPath
  • 没有使用按钮,因为我们有 imageView 来显示图像和 didSelectrow 在索引路径功能供选择。
  • @Anbu.Karthik, var selectedIndexPath:IndexPath?全局创建
  • 有什么问题.. 改变图像?或无法选择多部分..按钮也有图像属性..单选按钮..使用uIbutton bcz更方便。

标签: ios swift uitableview


【解决方案1】:

对于单节表视图,您可以使用selectedIndexPath 来存储选定的 indexPath。对于多节表视图,您需要一个 indexPaths 数组

var selectedIndexPathArr: [IndexPath?] = Array(repeating: nil, count: 3)//3 is number of sections

然后在 didSelect 方法中将选定的 indexpath 存储在其部分索引中

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 方法中比较当前 indexpath 与数组中的 indexpath 取决于当前部分

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多