我做了一个扩展的 tableViewCell ,我得到了一个变量的默认值 false 。如果值为 false ,则单元格会缩小,当 true 时,单元格会展开。问题是当单元格的值为真时我希望所有其他单元格值为 false ,我在挣扎。以下是我的代码:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let content = datasource[indexPath.row]
//Here content.expand = false by default in other class
if indexPath.row == 0 {
print("0 row")
content.expanded = !content.expanded
} else if indexPath.row == 1 {
print("1 row")
content.expanded = !content.expanded
} else if indexPath.row == 2 {
print("2 row")
content.expanded = !content.expanded
}
tableView.reloadRows(at: [indexPath], with: .automatic)
}
我不希望同时展开两个单元格。请帮忙。
答案 0 :(得分:2)
首先声明此变量
var selectedIndex: IndexPath?
接下来,这是您的选择代码:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if(selectedIndex != indexPath){ // It's not the expanded cell
var indicesArray = [IndexPath]()
if(selectedIndex != nil){ //User already expanded other previous cell
let prevExpandedContent = datasource[(selectedIndex?.row)!]
prevExpandedContent.expanded = !prevExpandedContent.expanded
indicesArray.append(selectedIndex!)
}
// Assign new expanded cell
selectedIndex = indexPath
let currentExpandedContent = datasource[indexPath.row]
currentExpandedContent.expanded = !currentExpandedContent.expanded
indicesArray.append(indexPath)
tableView.reloadRows(at: indicesArray , with: .automatic)
}
}
希望它能简化您的要求。