简体   繁体   中英

Swift tableview cell select to change checkbox image

I am trying to implement custom button check box in tableview cell. I have done checkbox when user clicks cell button it can change check and uncheck but if you click tableview cell also I needs to operate the check box

If possible please give some idea for radio button functionality because I am doing both.

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

You can get the selected cell in didSelectRowAt delegate and set the checkmark.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM