【问题标题】:UIButton state changing while scrolling the tableview with multiple sections - SwiftUIButton 状态在滚动带有多个部分的 tableview 时发生变化 - Swift
【发布时间】:2018-07-21 12:30:17
【问题描述】:

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

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 {


    }

}

【问题讨论】:

    标签: swift uitableview uibutton


    【解决方案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 
    }
    

    【讨论】:

    • 你能提供一些样品吗?
    • 单选按钮行位于部分下方。
    • 您也可以在上面的答案中使用 tag 属性代替 indexpath 。
    • @shubham 它需要再次从字符串中处理行和部分,是的,这是另一种选择
    • 您可以将其存储在全局变量中,也可以在为按钮设置标签时使用变量。然后不会发生额外的处理
    猜你喜欢
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多