自定义 UITableViewCell 按钮操作?

Custom UITableViewCell button action?(自定义 UITableViewCell 按钮操作?)
本文介绍了自定义 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);
}

有什么建议吗?谢谢.

推荐答案

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

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...

瞧,您不仅拥有 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 按钮操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Get an event when UIBarButtonItem menu is displayed(显示UIBarButtonItem菜单时获取事件)