Tarvo Mäesepp Tarvo Mäesepp - 3 months ago 32
iOS Question

Expand tableview cell on button click

I did some easy trick with constraints. I made

tableView
cell
which is expandable. On
cell
click it opens new cell(black)(Below is image for easier understanding).

My question is how can I make it work with the button which is inside the top cell which looks like "V". I want it at least to rotate like 90° if
cell
is clicked. How could I achieve it.

This is how I made it to expand:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if(selectedIndex == indexPath.row){
return 210
}else{
return 135
}
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (selectedIndex == indexPath.row){
selectedIndex = -1
}else{
selectedIndex = indexPath.row
}

self.productstable.beginUpdates()
self.productstable.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
self.productstable.endUpdates()
}


It looks like this:

enter image description here

Answer

You can achieve using closure:

typealias arrowButtonTappedBlock = (button:UIButton) -> Void

declare a closure in your custom cell like below:

var arrowButtonTapped : arrowButtonTappedBlock!

and on arrow button click's action call the closure like below:

if arrowButtonTapped != nil {
            arrowButtonTapped(button: sender as! UIButton)
        }

and in cellForRowAtIndexPath: set the closure and perform the action you were performing in didSelectRowAtIndexPath:

cell!.arrowButtonTapped = { (button:UIButton) -> Void in

                if (self.selectedIndex == indexPath.row){
                    self.selectedIndex = -1
                }else{
                    self.selectedIndex  = indexPath.row
                }

                self.tableview.beginUpdates()
                self.tableview.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
                self.tableview.endUpdates()
} 
Comments