Ios Swift tableview单元格选择以更改复选框图像

Ios Swift tableview单元格选择以更改复选框图像,ios,swift,tableview,Ios,Swift,Tableview,我试图在tableview单元格中实现自定义按钮复选框。我已经完成了复选框,当用户单击单元格按钮时,它可以更改选中和取消选中,但如果您单击tableview单元格,我也需要操作复选框 如果可能的话,请给出一些单选按钮功能的想法,因为我两者都在做 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:MyCust

我试图在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()
    }
您可以在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)
    }
}

哇,帮了大忙@Rakesha Shastri。顺便问一下,如何实现单选按钮功能?@iosdev堆栈溢出中已经有很多单选按钮,您可以很容易地找到它们。但是,如果它们不符合您的要求,您可以提出另一个问题,具体说明您的确切用例,人们会帮助您解决问题;谢谢你,伙计。我试试看。现在,我放置了我的单元格按钮,单击以获取单元格标签值,但得到一个错误线程1:致命错误:在展开可选值时意外地发现了nil。@iosdev再次重申,您应该避免以注释形式提出新问题。它们应始终单独张贴。这个错误是一个非常普遍的错误,它的解决方案是stackoverflow。提出一个新问题,提供必要的代码,并在给出错误的行上做标记。但首先尝试搜索是否已经被询问和回答。更新数据模型selectedRows,然后在indexPath处重新加载行,这将是一种更干净的方法。它避免了在cellForRowAt和didSelectRowAt之间重复大量代码。这是什么代码?这是对你问题的某种回答吗?这是一个新问题吗?不要只发布没有解释的代码。
// https://stackoverflow.com/questions/47300399/how-to-select-table-view-row-selection-with-custom-checkbox-button

import UIKit

class MyCustomCell: UITableViewCell {

    @IBOutlet weak var checkBox: UIButton!
    @IBOutlet weak var myCellLabel: UILabel!
}

class UpdateViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    // These strings will be the data for the table view cells
    var animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    var selectedRows:[IndexPath] = []

    // These are the colors of the square views in our table view cells.
    // In a real project you might use UIImages.
    let colors = [UIColor.blue, UIColor.yellow, UIColor.magenta, UIColor.red, UIColor.brown]

    // Don't forget to enter this in IB also
    let cellReuseIdentifier = "cell"

    override func viewDidLoad() {
        super.viewDidLoad()

        // Remove unused array
        tableView.tableFooterView = UIView()
        //tableView.allowsSelection = false

        tableView.delegate = self
        tableView.dataSource = self
    }

    // number of rows in table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.animals.count
    }

    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).")

        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:"uncheck.png"), for: .normal)
        } else {
            self.selectedRows.append(indexPath)
            cell.checkBox.setImage(UIImage(named:"check.png"), for: .normal)

            let indexPath = tableView.indexPathForSelectedRow //optional, to get from any UIButton for example
            let currentCell = tableView.cellForRow(at: indexPath!) as! MyCustomCell
            print(currentCell.myCellLabel.text ?? "")
        }
    }

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

            let center = sender.center
            let point = sender.superview!.convert(center, to:self.tableView)
            let indexPath = self.tableView.indexPathForRow(at: point)
            let cell = self.tableView.cellForRow(at: indexPath!) as! MyCustomCell //Add superview on the basis of your button hierarchy in the cell
            let cell_labelvalue =  cell.myCellLabel!.text
            print(cell_labelvalue ?? "")

        }
        self.tableView.reloadData()
    }

    @IBAction func selectAllBtnAction(_ sender: UIBarButtonItem) {
        self.selectedRows = getAllIndexPaths()
        self.tableView.reloadData()
    }

    func getAllIndexPaths() -> [IndexPath] {
        var indexPaths: [IndexPath] = []
        for j in 0..<tableView.numberOfRows(inSection: 0) {
            indexPaths.append(IndexPath(row: j, section: 0))
        }
        return indexPaths
    }


    @IBAction func cancelPopup(_ sender: Any) {
        self.removeAnimate()
    }

    @IBAction func donePopUp(_ sender: AnyObject) {
        self.removeAnimate()
    }

    func showAnimate()
    {
        self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
        self.view.alpha = 0.0;
        UIView.animate(withDuration: 0.25, animations: {
            self.view.alpha = 1.0
            self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
        });
    }

    func removeAnimate()
    {
        UIView.animate(withDuration: 0.25, animations: {
            self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
            self.view.alpha = 0.0;
        }, completion:{(finished : Bool)  in
            if (finished)
            {
                self.view.removeFromSuperview()
            }
        });
    }
}