Reputation: 1557
I made an expanding tableViewCell and I got a default value of a variable which is false. If the value is false then Cell shrinks, when its true then cell expand. Problem is when a value of a cell is true I want all the other cell value to be false, which I am struggling. Here is my code below:
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)
}
I do not want two cell to be expanded at the same time. Please help.
Upvotes: 0
Views: 36
Reputation: 1318
First declare this variable
var selectedIndex: IndexPath?
Next, here is your selection code:
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)
}
}
Hope it will simplify your requirement.
Upvotes: 1