Search code examples
iosxcodeanimationuitableviewreloaddata

Custom Row Animations for UITableViewCell


When I need to refresh UITableView I need some custom animations. I look for something like :

[self.table reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationLeft];

but to set my own animations. It would be perfect if this animation would be on UITableViewCell bases, because I need to animate onelly some of the elements in cell.

What I try to do:

I have custom cell like this

 ___________________________________
|  lable   |separator|  lable 2     |
 -----------------------------------

I would like lable 2 to swipe left or right, but not the whole cell.

Marko


Solution

  • in .h you will have reloadInWithMyOwnAnimation BOOL variable. Before you reload the section set it as YES. after reloading you set it as NO.

        reloadingWithMyOwnAnimation = YES;
    
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationLeft];
    
        reloadingWithMyOwnAnimation = NO;
    
    
    
        - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
            UITableViewCell *myCustomCell = cell;
    
            BOOL swipeLeft = YES;
    
    
            if (reloadingWithMyOwnAnimation == YES) {
    
    
                [UIView animateWithDuration:0.8f animations:^{
    
                    if (swipeLeft) {
                        //Swipe Right
    
                        //Get the label frame
                        CGRect myLabelFrame = myCustomCell.textLabel.frame;
    
    
                        //Set it to 0
                        myLabelFrame.origin.x = 0;
    
                        //Move it to Right
                        myLabelFrame.origin.x += cell.bounds.size.width;
    
    
                        //Set the frame of the label
                        [myCustomCell.textLabel setFrame:myLabelFrame];
    
    
                    }
                    else{
                        //Swipe Left
    
                        //Get the label frame
                        CGRect myLabelFrame = myCustomCell.textLabel.frame;
    
    
                        //Set it to 0
                        myLabelFrame.origin.x = 0;
    
                        //Move it to Left
                        myLabelFrame.origin.x -= cell.bounds.size.width;
    
    
                        //Set the frame of the label
                        [myCustomCell.textLabel setFrame:myLabelFrame];
    
    
    
                    }
    
                    [myCustomCell layoutSubviews];
    
    
                } completion:^(BOOL finished) {
    
                    NSLog(@"Done");
    
    
                }];
    
    
            }
    }
    

    enter image description here