Question

I created a custom table view which has custom cells, Each cell contains an image and a button (amongst other text)

I want to be able to change the image in the UIImageView when the button is clicked, I am able to get the click event. I however am having a difficult time changing the image.

I have attempted to get the entire cell in order to change the image using that :

   UIButton *senderButton = (UIButton *)sender;
    NSIndexPath *path = [NSIndexPath indexPathForRow:1 inSection:senderButton.tag];


    LocationCardCell* cell = (LocationCardCell *) senderButton.superview.superview.superview;

    if ([cell.class isSubclassOfClass:[LocationCardCell class]]) {
        NSLog(@"cell is RIGHT CLASS!!!");
    }else{
        NSLog(@"cell is not THE RIGHT CLASS!!!");
    }

    UIView *cellContentView = (UIView *)senderButton.superview;
    LocationCardCell *cell1 = (LocationCardCell *)cellContentView.superview; 
    if ([cell1.class isSubclassOfClass:[LocationCardCell class]]) {
        NSLog(@"cell1 is RIGHT CLASS!!!");
    }else{
        NSLog(@"cell1 is not THE RIGHT CLASS!!!");
              }

Can somebody please let me know how to go about getting the cell from the button click?

Was it helpful?

Solution

Keep this method in your arsenal...

- (NSIndexPath *)indexPathWithSubview:(UIView *)subview {

    while (![subview isKindOfClass:[UITableViewCell self]] && subview) {
        subview = subview.superview;
    }
    return [self.tableView indexPathForCell:(UITableViewCell *)subview];
}

Then,

- (IBAction)pressed:(id)sender {

    NSIndexPath *path = [self indexPathWithSubview:(UIButton *)sender];
    LocationCardCell* cell = (LocationCardCell *)[self.tableView cellForRowAtIndexPath:path];

   // carry on happily

But not too happily. You question doesn't state what you plan to do with that cell once you have it. The generally right approach to modifying tableview cells is to modify your model, reload the cell, and then account for that change in the datasource (tableView:cellForRowAtIndexPath:).

A more conventional pattern would be to use the indexPath we just found to dereference your model, modify it, then reload.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top