首页 > 解决方案 > Swift tableview 单元格选择以更改复选框图像

问题描述

我正在尝试在 tableview 单元格中实现自定义按钮复选框。当用户单击单元格按钮时,我已经完成了复选框,它可以更改选中和取消选中,但是如果您单击 tableview 单元格,我还需要操作复选框

如果可能的话,请对单选按钮功能提供一些想法,因为我两者都在做。

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell

        cell.myCellLabel.text = self.animals[indexPath.row]

        if selectedRows.contains(indexPath)
        {
            cell.checkBox.setImage(UIImage(named:"check.png"), for: .normal)
        }
        else
        {
            cell.checkBox.setImage(UIImage(named:"uncheck.png"), for: .normal)
        }
        cell.checkBox.tag = indexPath.row
        cell.checkBox.addTarget(self, action: #selector(checkBoxSelection(_:)), for: .touchUpInside)
        return cell
    }

    // method to run when table view cell is tapped
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }

    @objc func checkBoxSelection(_ sender:UIButton)
    {
        let selectedIndexPath = IndexPath(row: sender.tag, section: 0)
        if self.selectedRows.contains(selectedIndexPath)
        {
            self.selectedRows.remove(at: self.selectedRows.index(of: selectedIndexPath)!)
        }
        else
        {
            self.selectedRows.append(selectedIndexPath)
        }
        self.tableView.reloadData()
    }

标签: iosswifttableview

解决方案


您可以在委托中获取选定的单元格并设置复选标记。didSelectRowAt

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    guard let cell = tableView.cellForRow(at: indexPath) as? MyCustomCell else {
        return
    }
    if self.selectedRows.contains(indexPath) {
        self.selectedRows.remove(at: self.selectedRows.index(of: indexPath)!)
        cell.checkBox.setImage(UIImage(named:"unccheck.png"), for: .normal)
    } else {
        self.selectedRows.append(indexPath)
        cell.checkBox.setImage(UIImage(named:"check.png"), for: .normal)
    }
}

推荐阅读