UITableView: Display Message In Empty Table View

Display Message In Empty Table

There are times where there are no data available to be displayed in the Table View. In cases like this we can take of the backgroundView property of the TableView. We can set the backgroundView property to a UILabel with a message.

#import "ViewController.h"
@interface ViewController ()

@implementation ViewController
- (NSInteger)numberOfSectionsInTableView: (UITableView *) tableView{
    //assuming some_table_data respresent the table data
    if (some_table_data == nil) {
        //create a lable size to fit the Table View
        UILabel *messageLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0,
        //set the message
        messageLbl.text = @"No data is avaible";
        //center the text
        messageLbl.textAlignment = NSTextAlignmentCenter;
        //auto size the text
        [messageLbl sizeToFit];
        //set back to label view
        self.tableView.backgroundView = messageLbl;
        //no separator
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        return 0;
    //number of sections in this table
    return 1;

//the number of cells
- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //return 0 because we have no data
    return 0;

//get the cell
- (UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    return cell;


Cookbook Category: