Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A placeholder text to tableview if the datasource is empty

I want to display a text to user to inform that there is no content in the data source. For example you can see this kind of behavior in contacts App if you don't have contacts it says it at the middle of the table with gray text. Is there easy way to do this or do I have to use some trick like creating empty cells or something.. Thanks!

like image 340
Samuli Lehtonen Avatar asked Mar 07 '11 21:03

Samuli Lehtonen


2 Answers

There isn't (AFAIK) any built-in way to have a table view display a message when empty. You could have tableView:numberOfRowsInSection: return 1 if the datasource is empty and tableView:cellForRowAtIndexPath: return a "dummy" cell saying there is no data. Or you could just add your own view to display the appropriate message, ignoring the (empty) table view completely.

like image 174
Anomie Avatar answered Oct 20 '22 11:10

Anomie


Here's a short and sweet solution.

First step, in your UITableViewController initialization, add:

UILabel *placeholder = [[UILabel alloc] init];
placeholder.font = [placeholder.font fontWithSize:20];
placeholder.numberOfLines = 0; // Use as many lines as needed.
placeholder.text = NSLocalizedString(@"Your text here", nil);
placeholder.textAlignment = NSTextAlignmentCenter;
placeholder.textColor = [UIColor lightGrayColor];

placeholder.hidden = YES; // Initially hidden.
[self.tableView addSubview:placeholder];

self.placeholder = placeholder; // You'll need a reference to the placeholder.

Second step, in your UITableViewController, add:

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    self.placeholder.frame = self.tableView.bounds;
}

Last step, show/hide the placeholder when needed.

A better solution would be not using UITableViewController. Just add a tableView to a UIViewController and add a placeholder view to the UIViewController above the tableView. Use Auto Layout to have the placeholder centered vertically and horizontally. Finally, show/hide the placeholder when needed.

What do you guys think about that solution? Please comment.

like image 35
user3250560 Avatar answered Oct 20 '22 10:10

user3250560