Show tableView popover as soon as data is loaded

2019-03-22 10:16发布

问题:

i want to show a my Popover with a TableView just from the beginning, when the app loads. Problem is that the tableView doesn't have any content then. I am using that method:

 UIBarButtonItem *barItem = [self.toolbar.items objectAtIndex:0];
[self.popoverController presentPopoverFromBarButtonItem:barItem permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];

Now, my idea was to have a delegate method which is fired when the tableView finished fetching the data, but unfortunately nothing happens:

RootViewController.h:

@protocol RootDelegate <NSObject>
@optional
 -(void)didFinishLoading;
@end

RootViewController.m:

- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView initWithFrame:self.tableView.frame style:UITableViewStyleGrouped];
self.clearsSelectionOnViewWillAppear = NO;
[self setTitle:@"Zielscheiben"];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataSaved:) name:@"DataSaved" object:nil];

[[self delegate] didFinishLoading];
}

DetailViewController.m (conforms to the protocol)

 - (void)didFinishLoading
 {
    UIBarButtonItem *barItem = [self.toolbar.items objectAtIndex:0];
    [self.popoverController presentPopoverFromBarButtonItem:barItem permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];

  }

回答1:

The table view methods are threaded so your call at the end of viewDidLoad will happen at an unpredictable time, apparently here before the table is filled. I can't see any delegate method refering to the event "table is filled", so my best guess would be to keep your code and delay its execution :

[[self delegate] performSelector:@selector(didFinishLoading) withObject:nil afterDelay:1]

assuming 1 second will be enough for the table to be filled.

Another option you could explore is to fire it sometime in cellForRowAtIndexPath when you reckon the table has got enough data, but this is somehow more complex.



回答2:

You need to place your popover in viewDidAppear:

- (void)viewDidAppear {
    UIBarButtonItem *barItem = [self.toolbar.items objectAtIndex:0];
    [self.popoverController presentPopoverFromBarButtonItem:barItem permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}

viewDidAppear gets called after your UITableView has finished calling its datasource and tableview delegate methods.