Search code examples
swiftibactiondidselectrowatindexpathnsindexpath

Apply an IBAction only to a single cell


I have a tableView with prototypes cell; with this func I set cell height

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        return cellHeight
    }

with this action I change cell height touching up inside the UIButton

@IBAction func changeCellHeight(sender: UIButton)
    {
        if cellHeight == 44
        {
            cellHeight = 88
        } else {
            cellHeight = 44
        }
        tableView.beginUpdates()
        tableView.endUpdates()
    }

Now I need to change height only for selected cell (not for every cells); so I define var index: NSIndexPath! and I implement this func

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        index = self.tableView.indexPathForSelectedRow()!
        println("Cella " + "\(index)")
    }

As I expected in console Xcode prints the selected cell (<NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0} ).

So my trouble is how to use var index in the IBAction.

Thanks in advance.


Solution

  • To change your height based on selection, you don't need an IBAction if you are already implementing the didSelectRowAtIndexPath method.

    Just make a little change in your didSelectRowAtIndexPath method first-

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { 
       // You don't need to do this -> index=self.tableView.indexPathForSelectedRow()!
       index = indexPath;
       println("Cella " + "\(index)")
    
       tableView.beginUpdates()
       tableView.endUpdates()
    }
    

    And then a little change to your heightForRowAtIndexPath method-

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
        {
           if index == indexPath {
                return 88
            }
           else{
               return 44
           }
        }