3

I can't seem to handle a button click properly inside a custom UITableViewCell. It's a cell that contains a label and a button. I have the following code:

var cell = tableView.DequeueReusableCell (cellKey) as ApptHistoryCell;
if (cell == null)
{
    cell = _container.Cell;
    cell.SelectionStyle = UITableViewCellSelectionStyle.None;
}

if (InfoClicked != null)
{
    cell.ActionButton.TouchUpInside += InfoClicked;
}

InfoClicked is an event handler passed on in loop on cell creation. When the cell is re-used, this causes a null reference exception, because (I think) TouchUpInside is trying to call 2 handlers. Old one and the new one, which causes a crash. If I put the event handler inside cell == null if block, then the wrong action is shown.

How can I handle the click properly?

Thanks!

Greg R
  • 1,670
  • 4
  • 26
  • 46

3 Answers3

5

The way I handle buttons inside custom cells:

  • I define an IBAction that I connect to a UIButton event inside the custom cell
  • I define a delegate and a delegate method for the cell to handle the button action
  • The IBAction calls that delegate method
  • When defining your cells in cellAtRow... I set the tableViewController to be the delegate. cell.delegate=self;
  • I do whatever action I would like to do inside that delegate method in the tableViewController

Makes sense?

JP Hribovsek
  • 6,707
  • 2
  • 21
  • 26
0

you should create your cell from a xib file, which already connects the buttons to the owner's targets (the view controller).

Sagi Mann
  • 2,967
  • 6
  • 39
  • 72
-3

In your custom cell just locate your button at IB and make connection with the property.

Now, in the controller at cellForRowAtIndexPath, what you need, just tag that button, say:

(MyCustomCell*)cell.myButton = indexPath.row;

Now, after that just set the click event like that:-

[(MyCustomCell*)cell.myButton addTarget:self action:@selector(NeedFunctionToCall:) forControlEvents:UIControlEventTouchUpInside];

Now, at same view controller, implement that required method, like that:

-(void)NeedFunctionToCall:(id)sender
{
 NSLog("Got the event :-> %d, from the cell/button",[sender tag]);
}
Kara
  • 6,115
  • 16
  • 50
  • 57
Mohit_Jaiswal
  • 840
  • 6
  • 10