Send Row and Section through Tag in Button Swift

Greg Peckory picture Greg Peckory · Sep 2, 2015 · Viewed 8.3k times · Source

I have this inside cellForRowAtIndexPath

   cell.plusBut.tag = indexPath.row
   cell.plusBut.addTarget(self, action: "plusHit:", forControlEvents: UIControlEvents.TouchUpInside)

and this function outside:

func plusHit(sender: UIButton!){
    buildings[sender.tag].something = somethingElse
}

Is it possible to send the indexPath.row and indexPath.section, or some alternative??

Thanks!

EDIT

I approached it like this:

My Custom Button

class MyButton: UIButton{

    var myRow: Int = 0
    var mySection: Int = 0

}

My Custom Cell

class NewsCell: UITableViewCell{

    @IBOutlet weak var greenLike: MyButton!

In CellForRowAtIndexPath

    cell.greenLike.myRow = indexPath.row

I get an error on this line.

Answer

Caleb picture Caleb · Sep 2, 2015

Is it possible to send the indexPath.row and indexPath.section, or some alternative??

If you impose a limit on the number of possible rows in a section, you can combine the two into a single number. For example, if you're willing to say that there will always be fewer than 1000 rows in a given section, you can use:

cell.plusBut.tag = (indexPath.section * 1000) + indexPath.row

and then use mod and division operators to recover:

row = sender.tag % 1000
section = sender.tag / 1000

Another possibility is to check the button's superview (and it's superview, etc.) until you find the cell. Once you have the cell, you can get the index path for that cell from the table.

A third option, perhaps the best one, is to have the button target the cell rather than some other object. The cell can then trigger an action in the view controller or other object using itself as sender.