Chethan Shetty Chethan Shetty - 16 days ago 5
iOS Question

UIButton click event getting called multiple times inside custom UITableViewCell

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.

Answer

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 ();
Comments