Search code examples
iosuitableviewcell

Find Out Which Section Button Belongs To In UITableView When Clicked Inside Cell


I am trying to change the value of an element of an array depending which section a button is clicked in. For example say I have this array numbers = [0,0,0,0,0] and I want to change the first element to 5. I insert 5 into the cell of the first section and click done in that same section and the array will now read [5,0,0,0,0]. Is there a way to know which section the button belongs to?

Right now I have two separate classes. One for the custom cell and one for the tableview. Both of the have an outlet to the button. When the button is clicked the custom cell class changes a temporary global number to the inserted number. And inside the table class I want the button action to take that global number and insert in into the element that is the same number as the section the button belongs to. Except I don't know how to find out which section it belongs to.

Can anyone help me out with this? I'm writing in Swift btw.


Solution

  • If you only need the section (not the section and row) of the index path of the cell containing the tapped button, you could tag the button with the section number (Int) when you configure the table view cell:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("MyIdentifier", forIndexPath:indexPath) as! MyCustomTableViewCell
    
        cell.myCustomButton.tag = indexPath.section
    
        // Remove all existing targets (in case cell is being recycled)
        cell.myCustomButton.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
    
        // Add target
        cell.myCustomButton.addTarget(self, action:"buttonAction:", forControlEvents:.TouchUpInside)
    
        return cell
    }
    
    func buttonAction(sender:AnyObject)
    {
        if let button = sender as UIButton{
            println("Tapped Button in section: \(button.tag)")
        }
    }
    

    If you need both the section AND the row, you're better off storing the whole index path. For that, you can either use a custom UIButton subclass with a property of type NSIndexPath, or store it in the table view cell. But the second solution is a bit messy since you have to access the table cell (and then, the index path) from the button by using superview, etc., and this relies on the table cell's subview structure. I'm not sure if the parent view of your button is the table cell itself, or its "content view" (I'm a bit rusty right now...)