Yash R Yash R - 1 year ago 163
iOS Question

Swift 3 - Collapse other UITableViewCell when current cell is expanded

I am fresher iOS Development.I am trying to expand my

UITableViewCell
and I can expand cells. But I want to collapse the
UITableViewCell
which are not selected.

What I am trying in code:-

var expandedCells = [Int]()
@IBOutlet weak var tableVieww:UITableView!
@IBAction func buttonPressed(_ sender: AnyObject) {
// If the array contains the button that was pressed, then remove that button from the array
if expandedCells.contains(sender.tag) {
expandedCells = expandedCells.filter({ $0 != sender.tag})
}
// Otherwise, add the button to the array
else {
expandedCells.append(sender.tag)
}
// Reload the tableView data anytime a button is pressed
tableVieww.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! exampleCell
cell.myButton.tag = indexPath.row
return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Set the row height based on whether or not the Int associated with that row is contained in the expandedCells array
if expandedCells.contains(indexPath.row) {
return 212
} else {
return 57
}
}


Please Help me.

Answer Source

You can maintain a variable for maintaining the selected index as below,

var expandedIndexPath: IndexPath?

Then update your tableView delegate as follows,

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    expandedIndexPath = indexPath // Update the expandedIndexPath with the selected index
    tableView.reloadData() // Reload tableview to reflect the change
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    // Check wether expanded indexpath is the current index path and updated return the respective height
    if expandedIndexPath == indexPath {
        return 212
    } else {
        return 57
    }
}

This should work fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download