在自定义UITableViewCell中多次调用UIButton click事件

时间:2014-08-26 04:27:28

标签: ios uitableview xamarin.ios xamarin

我有一个自定义UITableViewCell,其中包含UIButton。单击该按钮时,将多次调用click事件。这是我正在使用的代码。

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;
}

知道为什么会这样吗?我正在重复使用细胞吗?

谢谢。

2 个答案:

答案 0 :(得分:3)

我迟到的回复我遇到了同样的问题并按照以下方式解决,可能对其他人有用:

cell.tnSave.TouchUpInside -= handler; 
cell.tnSave.TouchUpInside += handler;

这样可以防止多次向按钮的touchupinsider事件添加相同的处理程序。 handler可以定义为:

void handler(Object sender, EventArgs args)
        {
            Console.WriteLine("button clicked");
        }

答案 1 :(得分:1)

我相信你不应该每次都调用cell.BindData(),只有当你创建一个新的单元格时。否则,每次重新使用单元格时都会运行它。

分离绑定数据...拉出按钮触摸

internal void BindData()
{
    //some code
}

然后把按钮放在这里。

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 ();
相关问题