简体   繁体   中英

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.

One of the way would be to have delegate on the Cell and make the tableViewController implement the delegates when the action happens.

MyCell.h

@protocol MyCellDelegate

-(void)myCell:(MyCell*)cell reloadTableView:(id)sender;

@end

@interface MyCell : UITableViewCell

@property (nonatomic, weak) id <MyCellDelegate> delegate;

-(IBAction)reloadTableView:(id)sender;

@end

MyCell.m

@implementation MyCell

@property (nonatomic, weak) id <MyCellDelegate> delegate;

-(IBAction)reloadTableView:(id)sender;
{
    if(self.delegate)
    {
        [self.delegate myCell:self reloadTableView:sender];
    }
}

@end

Implement the delegate method in the tableViewController and do the task you want to perform.

-(void)myCell:(MyCell*)cell reloadTableView:(id)sender;
{
     CGPoint location = [sender locationInView:self.tableView];
     NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
    //Here is the indexPath
    [self.tableView reloadData];
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM