自定义UITableViewCell按钮动作? [英] Custom UITableViewCell button action?

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

问题描述

我一直在四处寻找解决方案,但似乎找不到适合我的解决方案。我有一个内置按钮的自定义单元格。我的问题是如何将indexPath传递给action方法?

I've been looking around to find a solution to this, but can't seem to find one that works for me. I have a custom cell with a button inside. My problem is how do I pass the indexPath to the action method?

现在我正在做

 [cell.showRewards addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];

在我的cellForRowAtIndexPath方法中,我的方法是:

In my cellForRowAtIndexPath method and my method is:

-(IBAction)myAction:(id)sender{
NSIndexPath *indexPath = [self.tableView indexPathForCell:(MyCustomCell *)[sender superview]];
NSLog(@"Selected row is: %d",indexPath.row);
}

有什么提示吗?谢谢。

推荐答案

虽然我觉得设置标签的按钮是一个要走的路。您可能需要编写代码以确保每次重用单元格时,都会在按钮对象上更新相应的标记。

While I feel setting tag for the button is one way to go. You might need to write code to make sure each time the cell gets reused, the appropriate tag gets updated on the button object.

相反,我觉得这可行。试试这个 -

Instead I have a feeling this could work. Try this -

-(IBAction)myAction:(id)sender
{
CGPoint location            = [sender locationInView:self.tableView];
NSIndexPath *indexPath      = [self.tableView indexPathForRowAtPoint:location];
UITableViewCell *swipeCell  = [self.tableView cellForRowAtIndexPath:indexPath];

NSLog(@"Selected row: %d", indexPath.row);
//......
}

基本上你是什么正在做的是获取与 tableView 相关的点击发生位置的坐标。获取坐标后, tableView 可以使用方法 indexPathForRowAtPoint:为您提供indexPath。你很高兴能够追求这个......

Essentially what you are doing is getting the coordinates of where the click happened with respect to your tableView. After getting the coordinates, tableView can give you the indexPath by using the method indexPathForRowAtPoint:. You are good to go after this...

Voila,你不仅仅是 indexPath 而且还有实际的点击发生的单元格。要从数据源获取实际数据(假设其NSArray),您可以执行 -

Voila, you have not just the indexPath but also the actual cell where the click happened. To get the actual data from your datasource (assuming its NSArray), you can do -

[datasource objectAtIndex:[indexPath row]];

这篇关于自定义UITableViewCell按钮动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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