How Do You Properly Configure An Empty View For UITableView?

584 views Asked by At

I need to set up a view that fills in the content area of a UITableView, and that is displayed whenever that table view is empty, hidden otherwise. That view contains an image, a label, and a button to perform a simple action. I was hoping to achieve two things:

1) leverage the backgroundView property of UITableView, and

2) leverage the storyboard as much as possible while minimizing the amount of code (maybe use a container view?).

However, I am not sure what is the best way to go about this. Insights appreciated, especially if you have already implemented this solution yourself.

2

There are 2 answers

0
Adam Jenkins On

You can probably do this a bunch of ways, but the easiest (conceptually) seems to be just use a container view that has two subviews:

  • A UITableView that is visible when it's not empty.
  • A UIView that holds your image/label/button that is visible when UITableView is empty.

Simply change their visibility depending on the content of the UITableView

Even if you only use the UITableView and set it's backgroundView to be the UIView to display when the UITableView is empty, virtually the same amount of work has to be done (you still have to create both views).

0
Kex On

First you want to set your background view in the viewDidLoad:

UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen]bounds].size.width, [[UIScreen mainScreen]bounds].size.height)];
//Make this clear and it will be the same as the tableView background color
[backgroundView setBackgroundColor:[UIColor clearColor]];
//We can add anything to this text of images
[backgroundView addSubview:imageView];
//This is the important part
[self.tableView setBackgroundView:backgroundView];

Now to hide or view the background view you need to add a bit of logic to - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView for example:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //Or wherever your data is
    if([self.data count]>0) {

        self.tableView.backgroundView.hidden=YES;
        return 1;

    }

    else {

        self.tableView.backgroundView.hidden=NO;


    }


    return 0;
}

Just check how many sections you have, if you have no sections in the table show the view. If you have sections then hide it.

Edit, obviously you could set up a UIView in the interface builder too if you like. Make sure it's the correct dimensions. Load if with something like:

UIView *view = [[[NSBundle mainBundle]
        loadNibNamed:@"MyView"
        owner:self options:nil]
         firstObject];

and again you need to set it: [self.tableView setBackgroundView:view];