【发布时间】:2018-02-14 09:07:13
【问题描述】:
我有一个包含部分(Category0、Category1、..)的 UITableView,并且特定部分的每一行都是一个 UITableView,它有一个部分是问题(Question1,..),而行是选项被回答(选项1,选项2,..)。 问题是当我单击特定类别中的按钮和特定问题(Category0,question1,option0)时,请参见 screenshot1,
立即点击另一个类别中的另一个按钮(类别1,问题2,选项0)见截图2,
和(Category4,question1,option0)见截图3。
下面的代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? insideTableViewCell
cell?.answerlabel.text = "option \(indexPath.row)"
cell?.initCellItem(id: (myObject?.id)! , answer: (myObject?.answerArray![indexPath.row] as? String)!)
return cell!
}
在一个自定义的 UITableViewCell 中,它位于 TableViewCell 内:
func initCellItem(id: Int , answer: String) {
radioButton.setImage( imageLiteral(resourceName: "unchecked"), for: .normal)
radioButton.setImage( imageLiteral(resourceName: "checked"), for: .selected)
radioButton.tag = id
radioButton.setTitle(answer, for: UIControlState.disabled)
radioButton.addTarget(self, action: #selector(self.radioButtonTapped), for: .touchUpInside)
}
@objc func radioButtonTapped(_ radioButton: UIButton) {
print(radioButton.tag)
print(radioButton.title(for: UIControlState.disabled) as Any)
let answer = radioButton.title(for: UIControlState.disabled) as Any
let StrId = String(radioButton.tag)
defaults.set(answer, forKey: StrId)
let isSelected = !self.radioButton.isSelected
self.radioButton.isSelected = isSelected
if isSelected {
deselectOtherButton()
}
}
func deselectOtherButton() {
let tableView = self.superview as! UITableView
let tappedCellIndexPath = tableView.indexPath(for: self)!
let section = tappedCellIndexPath.section
let rowCounts = tableView.numberOfRows(inSection: section)
for row in 0..<rowCounts {
if row != tappedCellIndexPath.row {
let cell = tableView.cellForRow(at: IndexPath(row: row, section: section)) as! insideTableViewCell
cell.radioButton.isSelected = false
}
}
}
【问题讨论】:
-
单元格被重复使用,和/或您处理选择的方式错误。但是没有代码,这很难说……
-
您必须跟踪数据源中的选择对象。所以当细胞被重新使用时,你可以从那里设置它!正如@Larme 建议的那样
-
你应该存储选择并重新加载tableView
-
你应该存储当前按钮状态(可能在字典中,如 [IndexPath: Bool] 或其他),并在
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell中恢复它 -
检查我的答案并遵循此格式
标签: ios swift uitableview uibutton