开发者

UITableView Separator Style Question

I have a tableview that is blank by default. User can add cells to it.

I want the separator lines to be clear when there are no cells, and grey 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, when I launch the app开发者_运维问答 with a blank table, and if I add cells, the grey lines are not there there until I restart the app. But if I start with cells there, then delete them, then re-add them, the lines are there. Any suggestions?


Maybe you are missing this?

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

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

The value of this property is one of the separator-style constants described in UITableViewCell Class Reference class reference. UITableView uses this property to set the separator style on the cell returned from the delegate in tableView:cellForRowAtIndexPath:.

That means the style wont change for cells that are already loaded. Just scrolling the table to force cells to redraw should make separators appearing...

You then have to :

  1. set it BEFORE cell is inserted

    OR

  2. reload tableView when the first cell is added

which is not easy to do with a NSFetchedResultsController, you should look into its delegate for a solution... or change direction, like hiding the tableView until you have a result maybe...


EDIT 2 : You can also simply add this :

[self.tableView reloadData];

but that's a dirty workaround that will just reload full tableView, losing most benefits of NSFetchedResultsController...


A quick fix 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];
    }
}


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

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

And to make sure you've really made it go away, set the seperatorColor property to whatever the background color of the view and cell would be:

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

So then even if somehow the above does not get called and the separator is still persisting - it would be the same color as what is behind it, therefore invisible.

Good luck.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜