如何制作允许各个部分进行单项或多项选择的UITableView?
我有一个UITableView
个多个部分。我想要一些部分允许多个选择,一些部分只允许一个选择。这就是我目前所拥有的:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
// Get the current question
if var question = self.questions[indexPath.section] as? MultipleChoiceQuestion {
// If question allows multiple selection set a checkmark and update question with selected answer
if question.hasMultiValue {
cell?.accessoryType = .checkmark
question.givenAnswer = question.answers[indexPath.row]
} else {
// Question is single selection only. This entire part goes wrong.
if let givenAnswerIsEmpty = question.givenAnswer {
cell?.accessoryType = .none
} else {
self.questions[indexPath.section].givenAnswer = question.answers[indexPath.row]
cell?.accessoryType = .checkmark
}
}
}
}
我的对象都有属性hasMultiValue
,表示某个部分是否应该允许多个选择。他们还拥有财产givenAnswer
,可以看作是" isSelected"旗。上面的代码仅适用于多选。
我一直在寻找解决方案。有一些问题,如this,但解决方案涉及使用委托方法didDeselectRowAt
。除非我实际取消选择不是我想要的当前单元格,否则这种方法不会被调用。
我想要的是例如:
如果你选择row1并将你的想法改为row2,你应该能够选择自动取消选择row1的row2。
答案 0 :(得分:0)
您没有尝试willSelectRowAt
?
您可以尝试此代码,这是在表视图控制器上测试的
var selectedItemInSection1: Int?
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
// Just return the same index path if the section was not the second one
guard indexPath.section == 1 else { return indexPath }
// Get the previously selected item, and deselect it
if let prev = selectedItemInSection1 {
tableView.deselectRow(at: IndexPath.init(row: prev, section: 1), animated: true)
}
// Save the newly selected item index, to be deselected when other is selected in the same section
selectedItemInSection1 = indexPath.row
// Select the item
return indexPath
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
guard indexPath.section == 1 else { return }
// If it is in the second section, indicate that no item is selected now
selectedItemInSection1 = nil
}