Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...