Search code examples
iphoneuitableviewuibuttonreloaddata

How to call an action from a Custom UITableViewCell for reload tableView


I have a simple problem: I can't call "[tableView reloadData]" from a UIButton in an UITableViewCell .m.

I have a tableView that show the UITableViewCell that contain a UIButton on each row. When I click on the button of the cell, I want to reloadData from my tableView.


Solution

  • As long as you hold a reference to your tableView, you should be able to reload the data by hitting a button. The easiest way to do this is to make a reference in your header file

    @interface MyClass ... {
        UITableView *myTableView;
        // all your other stuff;
    }
    // any methods and properties you want to declare;
    @end
    

    Then when you put your buttons into the cell in your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method, do something like the following

    UIButton *myButton = [UIButton buttonWithType:whateverTypeYouPick];
    [myButton addTarget:self action:@selector(reloadTableView) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:myButton];  // or cell.contentView or wherever you want to place it
    

    Then simply set up your action method

    - (IBAction)reloadTableView {
        [myTableView reloadData];
        // anything else you would like to do;
    }
    

    I tested this out and it works fine for me, so hopefully it does the trick for you as well