cateof cateof - 1 year ago 77
iOS Question

Handling an empty UITableView. Print a friendly message

I have a UITableView that in some cases it is legal to be empty. So instead of showing the
background image of the app, I would prefer to print a friendly message in the screen, such as:

This list is now empty

What is the simplest way to do it?

Answer Source

UITableView's backgroundView property is your friend.

In viewDidLoad or anywhere that you reloadData you should determine if there your table is empty or not and update the UITableView's backgroundView property with a UIView containing a UILabel or just set it to nil. That's it.

It is of course possible to make UITableView's data source do double duty and return a special "list is empty" cell, it strikes me as a kludge. Suddenly numberOfRowsInSection:(NSInteger)section has to compute the number of rows of other sections it wasn't asked about to make sure they are empty too. You also need to make a special cell that has the empty message. Also don't forget that you need to probably change the height of your cell to accommodate the empty message. This is all doable but it seems like band-aid on top of band-aid.