Question

Is there a best practice for animating a frame change in a UITableViewCell subview, but WITHOUT reloading the cell (either by reloadData or by reloading specific cells and sections).

Example: I have a simple UIView as a subview of a custom UITableViewCell, where the subview occupies some % of the total row width. I want to animate changes to the width of this UIView (while the container view, the UITableViewCell content view, stays the same), but without reloading, because the reloading animation options don't show the frame of the subview smoothly changing size in the way I'd like.

My initial solution was to iterate through the visible cells, and change each frame manually using a UIView animation block, e.g.

for (CustomCell *cell in [self.tableView visibleCells]])
{
    CGRect newFrame = CGRectMake(0.0,0.0,10.0,0.0); // different frame width
    [UIView animateWithDuration:0.5 animations:^{
        cell.block.frame = updatedFrame; // where block is the custom subview
     }];
}

but while this seems to work on iOS7, is leading to some funky and difficult to troubleshoot graphics kinks on iOS6; iterating through all the cells seems overkill.

Any recommendations for the best way to do this?

Was it helpful?

Solution

You can use the NSNotificationCenter to post a notification to inform each cell to change the width of that specific view.

When a cell is created you can register it to a specific notification:

[[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(receiveNotification:) 
    name:@"Notification"
    object:nil];

Then you can handle in each cell the notification and make the changes you need:

- (void) receiveNotification:(NSNotification *) notification
{
    CGRect newFrame = CGRectMake(0.0,0.0,10.0,0.0); // different frame width
[UIView animateWithDuration:0.5 animations:^{
    self.block.frame = updatedFrame; // where block is the custom subview
 }];
}

When you want to change the width you only need to post the event.

[[NSNotificationCenter defaultCenter] 
        postNotificationName:@"Notification" 
        object:self];

Do not forget to reuse each cell and when the cell is deallocated make sure you unregister that event.

[[NSNotificationCenter defaultCenter] removeObserver:self]; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top