开发者

Handling empty UITableView in UITableViewController

开发者 https://www.devze.com 2022-12-24 11:27 出处:网络
I have a UITableViewController that is populated with some data. If the data comes back empty, obviously the table is empty. What is the appropriate method to use to handle this case and put up someth

I have a UITableViewController that is populated with some data. If the data comes back empty, obviously the table is empty. What is the appropriate method to use to handle this case and put up something like a UILabel with "No Data Available".

I have b开发者_StackOverfloween using - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section but it's proven a bit cumbersome and I'm not longer confident it's the best place to do this.


I'd probably reverse the philosophy a bit to only show the UITableView when content is available, and have the UIView show your 'no content' available image until the content is ready.

Once the content has been fetched and is ready to be presented - animate or create the UITableView into the view hierarchy over the 'no content' image and ask it to reload its data. This will have it start working through it's datasource delegate callbacks.

At least this way you won't have to worry about showing a tableview with no data, and mixing concerns with UITableViewDataSource callback methods.


I just hid the tableview when there was no data instead. Simply subclass UITableView and override reloadData. You can also show/hide a text label appropriately to show no data available.

- (void)reloadData {
    [super reloadData];
    BOOL dataPresent = FALSE;
    int sections = [self.dataSource respondsToSelector:@selector(numberOfSectionsInTableView:)] ? [self.dataSource numberOfSectionsInTableView:self] : 1;
    for (int i = 0; i < sections; i++) {
        if ([self.dataSource tableView:self numberOfRowsInSection:i] > 0) {
            dataPresent = TRUE;
            break;
        }
    }
    self.hidden = !dataPresent;
    return;
}


Why not just change the backgroundView property of the UITableView to something appropriate when the table is empty? You can update the backgroundView property anytime you load or reloadData for your tableView. The backgroundView is automatically sized to the size of your tableView and you can customize it to have whatever pictures, text, controls you want for the empty case.

0

精彩评论

暂无评论...
验证码 换一张
取 消