自定义 UITableViewCell 和 IBAction [英] Custom UITableViewCell and IBAction

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

问题描述

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

I have a custom UITableViewCell on which I have added a button, I have associated that button on an IBAction in my viewController. Now the problem that i am facing is how do I know from which cell that button was created. When I present my viewController which has a table in it and has multiple rows (custom UITableViewCell), now when the user presses the button the action is getting called, but how do I know which row was it.

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

Because based on the row index I need to store some value.

我现在有一些线索,但我仍然不确定我将如何做,所以在我的 tableViewController cellForRowAtIndexPath 方法中,我必须做这样的事情

I have some clue on it now, but still I am not sure how will I do it, so it seems like on my tableViewController cellForRowAtIndexPath method I have to do something like this

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

然后我必须写一个方法

-(IBAction) addToCart:(id) sender

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

But still what I don't know is how do i get the row index in my addToCart method. Appreciate your help.

推荐答案

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

Ok, finally I got the answer, looking into different forums, people were suggesting to do something like this

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

in the custom table view controller in cellForRowAtIndexPath do this

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

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

where addToCart is name of UIButton in my customUITableViewCell. It didn't seems to work for me. So this is what I did

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

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

And then through interfacebuilder I associated the action of my button to addToCart IBAction on my table view controller.

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

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