3

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.

Fabio Cenni
  • 841
  • 3
  • 16
  • 30

1 Answers1

1

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
       }
    }
Natasha
  • 6,651
  • 3
  • 36
  • 58
  • Thanks a lot for your answer! But I think that I have to use UIButton: see following link http://stackoverflow.com/q/32238174/5143178 – Fabio Cenni Aug 27 '15 at 18:10
  • However could you explain what are the differences between index = self.tableView.indexPathForSelectedRow()! And index = indexPath? – Fabio Cenni Aug 27 '15 at 18:15
  • If you are inside the TableView's delegate method didSelectRowAtIndexPath, then the method is already providing the index path to you. See the method signature. So, you don't have to call the indexPathForSelectedRow() method. However, if you are anywhere else in that class like in an Action method, then you have no idea what is that indexPath. So, in that case you can call the indexPathForSelectedRow() method to get the selected indexPath. You could do the same in your didSelectRowAtIndexPath method, but that would just fail the purpose of implementing the didSelectRowAtIndexPath method then. – Natasha Aug 28 '15 at 06:44