我在这篇文章中使用了Cristik的回答:Drop-Down List in UITableView in iOS
代码工作正常,但我正在尝试创建逻辑,因此当用户单击一个闭合单元格时,每个其他打开的单元格都会关闭。因此,如果“帐户”单元格处于打开状态,则当用户单击“事件1”时,将打开事件并关闭“帐户1”。
我尝试了以下逻辑:
for (var x = 0; x < displayedRows.count; x++) {
let view = displayedRows[x]
if (view.isCollapsed == false && x != indexPath.row){
let range = x+1...x+view.children.count
displayedRows.removeRange(range)
let indexPaths = range.map{return NSIndexPath(forRow: $0, inSection: indexPath.section)}
tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
}
}
这是完整的功能:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let viewModel = displayedRows[indexPath.row]
if viewModel.children.count > 0 {
let range = indexPath.row+1...indexPath.row+viewModel.children.count
let indexPaths = range.map{return NSIndexPath(forRow: $0, inSection: indexPath.section)}
tableView.beginUpdates()
if viewModel.isCollapsed {
displayedRows.insertContentsOf(viewModel.children, at: indexPath.row+1)
tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
for (var x = 0; x < displayedRows.count; x++) {
let view = displayedRows[x]
if (view.isCollapsed == false && x != indexPath.row){
let range = x+1...x+view.children.count
displayedRows.removeRange(range)
let indexPaths = range.map{return NSIndexPath(forRow: $0, inSection: indexPath.section)}
tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
}
}
}
else {
displayedRows.removeRange(range)
tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
}
tableView.endUpdates()
}
viewModel.isCollapsed = !viewModel.isCollapsed
lastIndex = indexPath.row
}
我也尝试过此代码的变体但由于某些原因不断收到以下错误:由于未捕获的异常终止应用程序&#39; NSInternalInconsistencyException&#39;,原因:&#39;尝试插入行6进入第0部分,但更新后第0部分只有6行
我知道这是一个数据源问题,但我似乎无法找到解决方案。任何解决方案/或替代方式来实现这一点将不胜感激!谢谢