silverkid
silverkid

Reputation: 9563

Unable to access tableview property to get the index of button clicked in custom cell

i have created a custom table cell app . each cell contains buttons. i found on stackoverflow that the best way to find out whether button in row 1 was clicked or row 2 was clicked was to use this method

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

however i cannot use this because i am not getting an error at self.tableView.

this is because instead of using a UItableviewcontroller i am using UIViewcontroller and implementing the tableviewdelegate and tableviewdatasource. and the viewcontroller does not have any property tableview.

i cannot change the UIViewcontroller to UItableViewcontroller because everywhere in the code i am pushing the viewcontrollers using fileowner

So how can i get rid of the self.tableview error

Upvotes: 0

Views: 280

Answers (3)

Srijith Vijayamohan
Srijith Vijayamohan

Reputation: 915

My suggestion would be to keep the indexPath.row value in the custom cell object right when you create it.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   //Your cell creation logic here. 

    //Set indexpath in the custom cell. 
    cell.parentIndexPath = indexPath; 

    return cell;
}

and when the button is clicked, you can check it inside the custom cell object:

-(IBAction) buttonClicked: (id) sender {
  NSLog(@"User clicked on index path %@", self.parentIndexPath);

}

You have to declare the parentIndexPath in the custom cell header (.h) file.

@property (nonatomic, strong) NSIndexPath *parentIndexPath;

Upvotes: 2

Yohan
Yohan

Reputation: 1108

try to create property for your table

@property (strong, nonatomic) IBOutlet UITableView *myTableView;

then set myTableView instead of self.tableview. i tried this and this one works for me well

 CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:myTableView];
    NSIndexPath *indexPath = [buddyListTableView indexPathForRowAtPoint:buttonPosition];

    NSLog(@"Index Path  :%d",indexPath.row);

Upvotes: 1

Wain
Wain

Reputation: 119031

This should work:

CGPoint hitPoint = [sender convertPoint:CGPointZero toView:(UITableView *)self.view];

But you should have an @property which points to the table view really.

Upvotes: 0

Related Questions