简体   繁体   中英

UIbutton inside uitableviewcell not responding on scroll

I have uitableview with a custom cell in which I need to show some checkbox and radio button according to type in section. In cellForRowAt my code is

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                    let cell = tableView.dequeueReusableCell(withIdentifier: "PopupCell") as! PopupCell
                   //   self.mainTbl.beginUpdates()
                    cell.lblHeading.text = self.jsonNew[indexPath.section]["section_attributes_topping"][indexPath.row].stringValue
                    cell.lblPrice.text = "€"+self.jsonNew[indexPath.section]["section_attributes_price_topping"][indexPath.row].stringValue
                    cell.radioButton.tag = self.jsonNew[indexPath.section]["id"][indexPath.row].intValue


                    if self.jsonNew[indexPath.section]["type_attr"].stringValue == "radio"{
                        cell.radioButton.setImage(deselectedRadioImage, for: .normal)
                        cell.initCellItem()
                        cell.delegate = self


                    }else{
                        cell.radioButton.setImage(deselectedCheckboxImage, for: .normal)
                        cell.initCellCheckbox()
                        cell.delegate = self
                        cell.delegate_one = self
                    }

                    //cell.clipsToBounds = true
                  print(indexPath)
                   // self.mainTbl.endUpdates()
                    return cell
                }          // self.mainTbl.endUpdates()
    return cell
}

it is working fine if no scroll but when i scroll down and select then wrong button selected. I am new to ios development i know it is problem of cell reuse but how can i solve it. I did googling but not get any proper answer.

My cell code

                //
            //  PopupCell.swift
            //  AppAndEat
            //
            //  Created by Ravi Thakur on 11/08/18.
            //  Copyright © 2018 DevelopersGroup. All rights reserved.
            //

            import UIKit
            struct Product {
                var price = 0
                var name = ""
                var attr = ""
                var heading = ""
            }

            protocol PopupCellDelegate {
                func didToggleRadioButton(_ indexPath: IndexPath)
            }


            class PopupCell: UITableViewCell {

                var product : Product!

                private var counterValue = 1
                var productIndex = 0

                @IBOutlet weak var lblQty: UILabel!
                @IBOutlet weak var btnMinus: UIButton!
                @IBOutlet weak var btnPLusg: UIButton!
                var delegate: PopupCellDelegate?
                var delegate_one: PopupCellGetValue?
                @IBOutlet weak var lblPrice: UILabel!

                @IBOutlet weak var lblHeading: UILabel!
                @IBOutlet weak var radioButton: UIButton!
                override func awakeFromNib() {
                    super.awakeFromNib()
                    // Initialization code
                }

                override func setSelected(_ selected: Bool, animated: Bool) {
                    super.setSelected(selected, animated: animated)

                    // Configure the view for the selected state
                }
                func initCellItem() {

                    let deselectedImage = UIImage(named: "circle-shape-outline (1)")?.withRenderingMode(.alwaysTemplate)
                    let selectedImage = UIImage(named: "dot-and-circle (1)")?.withRenderingMode(.alwaysTemplate)
                    radioButton.setImage(deselectedImage, for: .normal)
                    radioButton.setImage(selectedImage, for: .selected)

                    radioButton.addTarget(self, action: #selector(self.radioButtonTapped), for: .touchUpInside)
                }
                func initCellCheckbox(){
                    let deselectedCheckBoxImage = UIImage(named: "blank-check-box")?.withRenderingMode(.alwaysTemplate)
                    let selectedCheckboxImage = UIImage(named: "check")?.withRenderingMode(.alwaysTemplate)
                    radioButton.setImage(deselectedCheckBoxImage, for: .normal)
                    radioButton.setImage(selectedCheckboxImage, for: .selected)
                    radioButton.addTarget(self, action: #selector(self.checkButtonTapped), for: .touchUpInside)
                }
                @objc func radioButtonTapped(_ radioButton: UIButton) {

                    let isSelected = !self.radioButton.isSelected
                    self.radioButton.isSelected = isSelected
                    if isSelected {
                        deselectOtherButton()
                    }
                    let tableView = self.superview as! UITableView
                    let tappedCellIndexPath = tableView.indexPath(for: self)!

                    delegate?.didToggleRadioButton(tappedCellIndexPath)
                   // delegate_one?.getAllValue(product: product, indexPath: tappedCellIndexPath)
                }

                func deselectOtherButton() {
                    let tableView = self.superview as! UITableView
                    let tappedCellIndexPath = tableView.indexPath(for: self)!
                    let indexPaths = tableView.indexPathsForVisibleRows
                    for indexPath in indexPaths! {
                        if indexPath.row != tappedCellIndexPath.row && indexPath.section == tappedCellIndexPath.section {
                            let cell = tableView.cellForRow(at: IndexPath(row: indexPath.row, section: indexPath.section)) as! PopupCell
                            cell.radioButton.isSelected = false
                        }
                    }
                }
                //function for checkboxes
                @objc func checkButtonTapped(_ radioButton: UIButton) {

                    let isSelected = !self.radioButton.isSelected
                    self.radioButton.isSelected = isSelected
                    if isSelected {
                        print(self.radioButton.isSelected)
                        self.radioButton.isSelected = isSelected
                        self.btnMinus.isHidden = false
                        self.btnPLusg.isHidden = false
                        self.lblQty.isHidden = false

                    }else{
                        self.btnMinus.isHidden = true
                        self.btnPLusg.isHidden = true
                        self.lblQty.isHidden = true
                        counterValue = 1
                        self.lblQty.text = "\(counterValue)"


                       // self.radioButton.isSelected = !isSelected
                    }
                    let tableView = self.superview as! UITableView
                    let tappedCellIndexPath = tableView.indexPath(for: self)!
                    delegate?.didToggleRadioButton(tappedCellIndexPath)

                }

                //function for plus minus qty

                @IBAction func clickMinus(_ sender: Any) {
                    if(counterValue != 1){
                        counterValue -= 1;
                    }
                    self.lblQty.text = "\(counterValue)"

                    let tableView = self.superview as! UITableView
                    let tappedCellIndexPath = tableView.indexPath(for: self)!
                    //delegate?.didToggleRadioButton(tappedCellIndexPath)
                    delegate?.checkPrice(tappedCellIndexPath, price: "\(counterValue)")
                }

                @IBAction func clickPlus(_ sender: Any) {
                    counterValue += 1;
                    self.lblQty.text = "\(counterValue)"
                }
            }

Looks like

let tableView = self.superview as! UITableView let tappedCellIndexPath = tableView.indexPath(for: self)! doesn't return the right indexPath for you.

Create something like that:

protocol PopupCellDelegate: class {
func didTap(_ cell: Cell)

}

class PopupCell: UITableViewCell {

weak var delegate: PopupCellDelegate?
@IBAction func radioButtonPressed(_ sender: Any) {
    delegate?.didTap(self)
}

}

class ViewController: UIViewController, PopupCellDelegate {

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = ...
    cell.delegate = self
    return cell
}

func didTap(_ cell: Cell) {
    let indexPath = self.tableView.indexPath(for: cell)
    cell.delegate?.didToggleRadioButton(indexPath)
}

Rebuild this for your cells and actions, it should work. If not, then i will think more about it)

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