Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Scott Evans
Scott Evans
4,236 Points

iOS UIButton events - Objective C @selector

Im having an issue which i can't seem to get my head around.

The situation is:

I have a UIButton within a SubClass of UITableViewCell ( for custom cell stuff). What i need to do is find a way to execute a method from the main view controller if one of these UIButtons is pressed within a table cell. This method needs to be passed particular data to allow me to reference it to actual data i will use for a manipulation.

Here is what I've tried so far

MainViewController.m

[cell.addButton addTarget:self action:@selector(addToNote:withPriceIndex:) forControlEvents:UIControlEventTouchUpInside];

In this example the selector gets called correctly but I'm not quite sure how to pass the variables that i need to be passed, to allow me to capture the data that button relates to.

If anyone who has experience working with selectors, or knows another solution it would be greatly appreciated!

Thank you in advance, Scott.

Scott Evans
Scott Evans
4,236 Points

Stone Preston , i believe you might be able to help me here if you get a chance.

Scott Evans
Scott Evans
4,236 Points

Okay, ive realised you cannot send custom parameters to an action:selector as it only takes the event sender & event.

Scott Evans
Scott Evans
4,236 Points

I guess my next question would be, how do i access the particular instance of the class that corresponds to a particular CustomTableViewCell button

1 Answer

Scott Evans
Scott Evans
4,236 Points

I think i found my own solution. I managed to find the indexPath of the cell where a button was pressed and then managed to use that to access my datasource and table view to get the required data & classes.

Below is the code just incase it helps anyone else.

-(void)addToNote:(id)sender{
    NSLog(@"Add to note");

    CGPoint buttonOriginInTableView = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonOriginInTableView];

    CoreDataClass *crData = [_fetchedResultsController objectAtIndexPath:indexPath];
    CustomTableCell *cell = (CustomTableCell *)[self.tableView cellForRowAtIndexPath:indexPath];
}