简体   繁体   中英

How to call a method from another view controller

I am trying to figure out how to take the -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; , method and call it from another view controller.

In LocationViewController.m

- (void)viewDidLoad {
  [super viewDidLoad];
  //save bar button item
  UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithTitle: @"Save" style: UIBarButtonItemStylePlain target: self action: @selector(saveButtonPressed)];

  self.navigationItem.rightBarButtonItem = saveButton;

  [self performSelector:@selector(saveButtonPressed) withObject:nil afterDelay:0.25];
}

-(void)saveButtonPressed {

    //I want to call the method here

}

In GameDetailsTableViewController.m

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

    static NSString *CellIdentifer1 = @"GameDetailsLocationCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifer1];

    cell.textLabel.text = @"hello world"

    return cell;
}

I am a beginner in IOS and I would greatly appreciate any help.

You cannot call cellForRowAtIndexPath , but you can trigger the datasource methods of tableview from another class. Heres how

Suppose you want to trigger cellForRowAtIndexPath of Class A from Class B's method someMethod

In Class Am

-(void)viewDidLoad{
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(somemethodToReloadtableview) name:@"NOTIFICATIONNAME" object:nil];
}
//Implement the method
-(void)somemethodToReloadtableview{
[self.customTableViewName reloadData];
}

Class Bm

-(void)methodFromWhichYouWantToTrigger{
 [[NSNotificationCenter defaultCenter]postNotificationName:@"NOTIFICATIONNAME" object:nil];
}

PS - This method will invoke all the datasource of tableview such as numberOfRows . Hope this helps

I am not sure why you want to call the tableView: cellForRowAtIndexPath: manually. If you want your table view to reload the data, you can call reloadData method on your table view.

[yourTableView reloadData];

And if you want to trigger this from another view controller, you can post a notification from the other view controller and listen to that from the one where table view exists. Saheb's answer describes how to post the notification and listen to that.

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