在自定义的UITableViewCell中多次调用UIButton点击事件

我有一个自定义的UITableViewCell里面有一个UIButton 。 点击button时,点击事件会被多次调用。 这是我正在使用的代码。

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

任何想法为什么发生这种情况? 我是否正确地重复使用单元格?

谢谢。

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

分离绑定数据的东西…拔出button触摸

 internal void BindData() { //some code } 

然后把button的东西放在这里

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

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

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

这将防止多次添加相同的处理程序到button的touchupinsider事件。 处理程序可以被定义为:

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