我如何制作一个 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一种解决方案涉及使用委托(delegate)方法 didDeselectRowAt
。除非我物理取消选择不是我想要的当前单元格,否则不会调用此方法。
我想要的是例如:
如果您选择第 1 行并改变主意到第 2 行,您应该能够选择第 2 行,这会自动取消选择第 1 行。
最佳答案
您没有尝试 willSelectRowAt
吗?
你可以试试这段代码,这是在 TableView Controller 上测试过的
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
}
关于ios - 具有单选和多选的 UITableView 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48745180/