I have a custom UITableViewCell
which has an UIButton
in it. When the button is clicked the click event is getting called multiple times. Here is the code what i am using.
CustomCell.cs
public static CustomCell Create ()
{
return ( CustomCell ) Nib.Instantiate ( null , null ) [0];
}
internal void BindData()
{
//some code
btnSave.TouchUpInside+= (object sender, EventArgs e) =>
{
Console.WriteLine("button clicked");
};
}
TableSource.cs
public override UITableViewCell GetCell (UITableView tableView,NSIndexPath indexPath)
{
CustomCell cell = tableView.DequeueReusableCell ( CustomCell.Key ) as CustomCell ?? CustomCell.Create ();
cell.BindData ();
return cell;
}
Any idea why is this happening? am i reusing the cells properly?
Thank you.
I believe you should not call cell.BindData() every time, only when you create a new cell. Otherwise you will be running it every time you re-use your cell.
separate the bind data stuff... pull out the button touch
internal void BindData()
{
//some code
}
and then put the button stuff in here.
var cell = tableView.DequeueReusableCell(CustomCell.Key) as CustomCell;
if (cell == null)
{
cell = CustomCell.Create ()
cell.btnSave.TouchUpInside+= (object sender, EventArgs e) =>
{
Console.WriteLine("button clicked");
};
}
cell.BindData ();
Its late reply I came across same problem and solved as follow,might be useful for others:
cell.tnSave.TouchUpInside -= handler;
cell.tnSave.TouchUpInside += handler;
This will prevent from adding same handler to button's touchupinsider event multiple time. handler can be defined as :
void handler(Object sender, EventArgs args)
{
Console.WriteLine("button clicked");
}