3

我有一个自定义 UITableViewCell,我在其上添加了一个按钮,我已将该按钮与我的 viewController 中的 IBAction 相关联。现在我面临的问题是我如何知道该按钮是从哪个单元格创建的。当我展示其中有一个表并且有多行(自定义 UITableViewCell)的 viewController 时,现在当用户按下按钮时,该操作被调用,但我怎么知道它是哪一行。

因为基于行索引我需要存储一些值。

编辑:我现在有一些线索,但我仍然不确定我将如何做到这一点,所以似乎在我的 tableViewController cellForRowAtIndexPath 方法上我必须做这样的事情

[cell.button1 addTarget:self action:@selector(addToCart:) forControlEvents:UIControlEventTouchUpInside];

然后我必须写一个方法

-(IBAction) addToCart:(id) sender

但我仍然不知道如何在我的 addToCart 方法中获取行索引。感谢你的帮助。

4

4 回答 4

20

好的,最后我得到了答案,查看不同的论坛,人们建议做这样的事情

在 cellForRowAtIndexPath 的自定义表格视图控制器中执行此操作

cell.addToCart.tag = indexPath.row;
[cell.addToCart addTarget:self action:@selector(addToCart:)    
                               forControlEvents:UIControlEventTouchUpInside];

其中 addToCart 是我的 customUITableViewCell 中 UIButton 的名称。它似乎对我不起作用。所以这就是我所做的

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

然后通过 interfacebuilder 我将按钮的操作关联到我的表视图控制器上的 addToCart IBAction。

于 2010-11-08T16:22:45.123 回答
5

少得多骇人听闻。

[cell.button1 addTarget:self action:@selector(addToCart:event:) forControlEvents:UIControlEventTouchUpInside];


- (void)addToCart:(id)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];

}
于 2012-07-09T18:07:46.830 回答
4

接受的答案不再起作用。请参考这个帖子

它是这样做的:

- (void)checkButtonTapped:(id)sender
{
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil)
    {
     ...
    }
}
于 2014-06-17T13:49:50.010 回答
0

许多开发人员使用自定义视图在旧版本 iOS 的表格视图中显示自定义单元格。如果您是其中之一,那么您将不得不面对一个问题,即您的按钮单击操作将不再适用于 iOS7。

如何解决这个问题:

你有两个选择:

选项 1:使用新表格单元创建新布局,而不是查看。并将所有布局再次放入表格单元格中。

我知道,这需要付出很多努力。如果您不想这样做,我们有一个非常小的 hack:选项 2

选项 2:为您的按钮创建一个 IBOutlet 并将此按钮添加为单元格内容视图的子视图。

[self.myCell.contentView addSubview:self.btn_click];

上面的代码行将 btn_click 添加为内容视图的子视图。现在按钮点击动作应该可以工作了。

于 2013-09-30T14:10:45.843 回答