滚动带有多个部分的tableview时,UIButton状态更改-Swift

时间:2018-07-21 12:30:17

标签: swift uitableview uibutton

我的表格视图中有多个部分,其中包含多个自定义单元格(具有单选按钮的单元格,具有复选框的单元格和具有文本字段的单元格)。问题在于单选按钮部分,单选按钮部分下只能选择一个单选按钮。选择后,我尝试滚动,选择了多个单选按钮。非常感谢。

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

行方法的单元格:

  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 个答案:

答案 0 :(得分:1)

tableView单元格被重用(滚动时发生),因此您需要通过保存选定的IndexPath并将其分配到cellForRowAt内来跟踪选定的那个

//

在您的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 
}