jcrowson
jcrowson

Reputation: 4290

Show label if Table View is empty

I'm using Core Data to store a project name and display it in a table view. When the table view is empty (no data in the database) it is blank. From a user perspective this isn't great, so I want to be able to display a label that says "No Projects".

How would I do this? I would need to:

  1. Check that the database is empty and set a BOOL
  2. if this BOOL is set to true or YES, show a label? or set the cell.textLabel.text as "No Projects"

If i'm on the right tracks I'd really appreciate some example code to give me a push in the right direction.

Thanks

Upvotes: 3

Views: 2856

Answers (3)

MANIAK_dobrii
MANIAK_dobrii

Reputation: 6032

There is a convenient lib for that: UITableView-NXEmptyView

As easy as:

tableView.nxEV_emptyView = yourView

UPD: There's something more flexible and up-to-date solution.

Upvotes: 1

jcrowson
jcrowson

Reputation: 4290

I ended up using the following code to check if my Core Data database is empty. Works brilliantly. This must go in the CoreDataController.m file.

NSLog(@"Total number of rows = %d ", totalNumberOfRowsInDatabase);

    if (totalNumberOfRowsInDatabase == 0)
    {

        NSLog(@"Database is empty");
        UIImage *image = [UIImage imageNamed:@"emptyTable.png"];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        [imageView setFrame:self.tableView.bounds];
        [self.tableView setBackgroundView:imageView];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.tableView setBackgroundColor:[UIColor clearColor]];

    }
    else 
    {
        [self.tableView setBackgroundView:nil];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [self.tableView setBackgroundColor:[UIColor whiteColor]];
    }

    return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];

Upvotes: 3

QED
QED

Reputation: 9923

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   if (section == mySection) return MAX(dataCount, 1);
   else // yadda
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   // yadda

   if ([indexPath section] == mySection) {
      if (dataCount == 0) return mySpecialCell;
   }


   // yadda
}

Upvotes: 1

Related Questions