Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

uitableview - Custom UITableViewCell and IBAction

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.

Edit: 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];

And then I have to write a method

-(IBAction) addToCart:(id) sender

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

in the custom table view controller in cellForRowAtIndexPath do this

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

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); 
 }

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...