Search code examples
iosobjective-ccore-animation

iOS UIView animation when table view scroll?


I want animation like home screen of this app.This screen has a view (with a label on it) on top and a table view under it. When i scroll the table the top view and title on it become small with animation and after a specific point it becomes like navigation bar with title in centre. And the same thing when i scroll down. Here is what i tried so far

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint offset = scrollView.contentOffset;
    NSLog(@"y is::: %f", offset.y);

    if (offset.y > 0 && offset.y < 16 && self.topView.frame.size.height > 64) {

        [UIView animateWithDuration:0.8 animations:^{

            CGRect rect = self.topView.frame;
            rect.size.height = rect.size.height-offset.y;
            self.topView.frame = rect;

        }completion:^(BOOL finish){

        }];

    }
    else if(offset.y <= 0 && offset.y > -16 && self.topView.frame.size.height < 80)
    {
        [UIView animateWithDuration:0.8 animations:^{

            CGRect rect = self.topView.frame;
            rect.size.height = 80;
            self.topView.frame = rect;

        }completion:^(BOOL finish){

        }];
    }

}

Note that my top view initial height is 80 and i want to make it 64 when scroll up and vice versa. with this code the view height animated but it depends upon animation duration.So if i scroll fast then it is not working properly.The original app i mentioned have very smooth animation. How could i achieve that? Screen shot of original App- enter image description here These screen shots showing three different scroll position, please note the "MySurgery" text on top.1- Larger text and right align. 2- small text and near centre position 3- smaller text and centralised(like navigation bar)


Solution

  • I think you dont need animation for this, you just need some calculations and setting frame of the top view. like,

        -(void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        CGPoint offset = scrollView.contentOffset;
    
        if (offset.y>0 && offset.y<64) {
            [topView layoutIfNeeded];
            CGRect viewFrame = topView.frame;
            viewFrame.size.height--;
            topView.frame = viewFrame;
        }
    }
    

    Note that layoutIfNeeded is required if your view is using autolayout