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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With