mercredi 24 février 2021

How can I make checkbox (UIButton) in cellForRowAt method of tableview?

Currently I am making the image change when the checkbox button is pressed, the code works fine, but every time the cell is updated, the checkbox button item and the cell operate separately...

I want to make the checkMarkButtonClicked function work in cellForRowAt.

I searched Google and YouTube all the examples but couldn't find a suitable answer. I'm also using a state config of tableViewCell option:

"State Config" set to "Selected" in storyboard attributes inspector

Here's my code:

// tableView Settings
extension HomeViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ListTableViewCell", for: indexPath) as! ListTableViewCell
        
        cell.todoLabel.text = list[indexPath.row].todoTask
        
        cell.colorCircle.backgroundColor = .black
        cell.colorCircle.layer.cornerRadius = cell.colorCircle.frame.size.width / 2
        cell.colorCircle.clipsToBounds = true
        //        cell.checkButton.setImage(UIImage(named: "checkBox"), for: .normal)
        
        cell.checkButton.addTarget(self, action: #selector(checkMarkButtonClicked(sender:)), for: .touchUpInside)
        return cell
    }
    
    @objc func checkMarkButtonClicked(sender: UIButton) {
        print("Button pressed")
        
        if sender.isSelected {
            // uncheck the button
            sender.isSelected = false
        } else {
            // checkmark into
            sender.isSelected = true
        }
        self.homeTableView.reloadData()
    }



Aucun commentaire:

Enregistrer un commentaire