ios - Swift 表格 View 单元格选择更改复选框图像

标签 ios swift tableview

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

如果可能,请提供有关单选按钮功能的一些想法,因为我正在做这两件事。

   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()
    }

最佳答案

您可以在 didSelectRowAt 委托(delegate)中获取所选单元格并设置复选标记。

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)
    }
}

关于ios - Swift 表格 View 单元格选择更改复选框图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52392711/

相关文章:

swift - windowDidLoad 没有被调用(再次)

ios - 在 Swift 中实现 PageViewController

iphone - 从其他类到 UITableView 的 NSIndexPath

ios - UITableViewHeaderFooterView 外观

ios - 仅在首次初始化自定义 UIView 时如何在 LayoutSubviews 中执行代码

ipad - AVURLAsset 拒绝加载视频

ios - 使用 Swift 生成 base64 url​​ 编码的 X.509 格式 2048 位 RSA 公钥?

arrays - Swift 中带有两个数组的 MultipleCollectionViews

swift - 在 Swift 中,如何使动态 tableView 单元格可选择,以便当按下它时它会传输到不同的 tableViewController?

iphone - Xcode 调试控制台输出已更改