UIButton state changing while scrolling the tableview with multiple sections - Swift

萝らか妹 提交于 2020-01-16 13:17:21

问题


I have multiple sections in my tableview with multiple custom cells(cell with radio button, cell with check box and cell with textfield). Problem is under section with radio button, only one radio button should be selectable under radio button section. After selecting, I have tried scrolling, multiple radio buttons are selected. Help much appreciated.

class RedioButtonCell: UITableViewCell {

var radioButtonDelegate: RedioCellDelegate?
  var cellindexPath : IndexPath?
@IBOutlet weak var btnRediouttion: UIButton?
@IBOutlet weak var lblTitle: UILabel?


override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}
}

Cell for row method:

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 if ((qaArray[indexPath.section]["Que"] as! [String:String])["type"]!) == CONTROL
    {
        let  cell = tableView.dequeueReusableCell(withIdentifier: "RedioButtonCell", for: indexPath) as! RedioButtonCell

     cell.btnRediouttion?.tag = Int("\(indexPath.section)" +  "\(indexPath.row)")!

        cell.lblTitle!.text = String(describing: ansDetailArray[indexPath.row]["survey_answer"]!)


let deselectedImage = UIImage(named:         "Radio_Unselected")?.withRenderingMode(.alwaysTemplate)
    let selectedImage = UIImage(named: "radio_Selected")?.withRenderingMode(.alwaysTemplate)
    btnRediouttion?.setImage(deselectedImage, for: .normal)
    btnRediouttion?.setImage(selectedImage, for: .selected)
    btnRediouttion?.addTarget(self, action:    #selector(self.radioButtonTapped), for: .touchUpInside)

         cell.cellindexPath = indexPath;
        return cell
    }
}
func radioButtonTapped(_ radioButton: UIButton) {
    print("radio button tapped")
    let isSelected = !(radioButton?.isSelected)!
    radioButton?.isSelected = isSelected
    if isSelected {


    }

}

回答1:


The tableView cells are reused ( happens when scrolling ) , so you need to keep track of the selected one by saving it's IndexPath and assign it inside cellForRowAt

//

declare this in your VC

 var currentIndex:IndexPath?

//

class RadioButton:UIButton {

  var indexPath:IndexPath
}

//

func radioButtonTapped(_ radioButton: RadioButton) {

    self.currentIndex = radioButton.indexPath
}

//

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

      if indexPath == currentIndex {
         // this should be selected
      }
      else {
         // Deselect this 
      }

      cell.radioButton.indexPath = indexPath 
}


来源:https://stackoverflow.com/questions/51456084/uibutton-state-changing-while-scrolling-the-tableview-with-multiple-sections-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!