UITableView Separator Style Question

I have a table view that is empty by default. The user can add cells to it.

I want the separator lines to be clear when there are no cells, and gray when there are cells.

I am using this code:

if ([[self.fetchedResultsController fetchedObjects] count] == 0) { self.routineTableView.separatorStyle = UITableViewCellSeparatorStyleNone; self.routineTableView.separatorColor = [UIColor clearColor]; } else { self.routineTableView.separatorColor = [UIColor grayColor]; } 

The problem is that when I run the application with an empty table, and if I add cells, there will not be gray lines until I restart the application. But if I start with the cells there, then I delete them, and then again add the rows there. Any suggestions?

+4
source share
3 answers

Perhaps you are missing it?

 ... else { self.routineTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine; // or you have the previous 'None' style... self.routineTableView.separatorColor = [UIColor grayColor]; } 

EDIT : You need this, but not only that ... According to Apple Documentation:

The value of this property is one of the delimiter style constants described in the UITableViewCell Reference Reference class. UITableView uses this property to set the separator style in the cell returned by the delegate in tableView:cellForRowAtIndexPath:

This means that the style will not change for already loaded cells. Just scrolling through the table to make cells redraw, separators should appear ...

Then you need to:

  • set it before inserting a cell

    OR

  • reload tableView when adding the first cell

which is not easy to do with NSFetchedResultsController , you should study its delegate to solve ... or change direction, for example, hide tableView until you get the result ...


EDIT 2 . You can also simply add this:

 [self.tableView reloadData]; 

but this is a dirty workaround that will simply reload the full tableView, losing most of the benefits of NSFetchedResultsController ...

+12
source

The quick fix that I usually do is:

 #pragma mark - UITableViewDelegate - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { if ([tableView respondsToSelector:@selector(setSeparatorStyle:)]) { [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone]; } } 
+1
source

This changes the logical flag of whether there will be a delimiter or not. Put this in viewDidLoad:

 self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; 

To make sure that you really removed it, set the seperatorColor property to the background color and cell color:

 // If the background is white self.tableView.separatorColor = [UIColor whiteColor]; 

So, even if somehow the above does not work out, and the separator is still preserved - it will be the same color as behind it, therefore invisible.

Good luck.

+1
source

All Articles