处理 UITableViewCell 内的按钮单击 [英] Handle button click inside UITableViewCell

查看:39
本文介绍了处理 UITableViewCell 内的按钮单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法在自定义 UITableViewCell 中正确处理按钮单击.它是一个包含标签和按钮的单元格.我有以下代码:

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 是在单元格创建时循环传递的事件处理程序.当单元格被重用时,这会导致空引用异常,因为(我认为)TouchUpInside 正在尝试调用 2 个处理程序.旧的和新的,导致崩溃.如果我将事件处理程序放在 cell == null if 块中,则会显示错误的操作.

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.

如何正确处理点击?

谢谢!

推荐答案

我处理自定义单元格内按钮的方式:

The way I handle buttons inside custom cells:

  • 我定义了一个连接到自定义单元格内的 UIButton 事件的 IBAction
  • 我为单元格定义了一个委托和一个委托方法来处理按钮动作
  • IBAction 调用该委托方法
  • 在 cellAtRow 中定义单元格时...我将 tableViewController 设置为委托.cell.delegate=self;
  • 我在 tableViewController 的委托方法中做我想做的任何操作

有意义吗?

这篇关于处理 UITableViewCell 内的按钮单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆