iosobjective-canimatewithduration

iOS animationWithDuration chaining first animation isn't showing


I have 2 animations with one calling the other, but only the later is actually happening. I am not sure with the issue is. I am new to iOS. I am trying to animate it up then down but only the down is happening.

Also, if I change the call from [self animateUp] to [self animateDown], no animation happens.

-(void)viewDidLoad
{
    [super viewDidLoad];
    [self.containerView addSubview:self.logoView = ({
        UIImageView *imageView = [UIImageView new];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.image = [UIImage imageNamed:@"thisImage"];
        imageView;
    })];
    [self animateUp];
}

- (void)animateUp
{
    [UIView animateWithDuration:1 animations:^{
        CGRect newFrame = CGRectMake(self.logoView.frame.origin.x, self.logoView.frame.origin.y - 40, self.logoView.frame.size.width, self.logoView.frame.size.height);
        self.logoView.frame = newFrame;
    } completion:^(BOOL finished) {
        [self animateDown];
    }];
}

- (void)animateDown
{
    [UIView animateWithDuration:1 animations:^{
        CGRect newFrame = CGRectMake(self.logoView.frame.origin.x, self.logoView.frame.origin.y + 40, self.logoView.frame.size.width, self.logoView.frame.size.height);
    self.logoView.frame = newFrame;
    } completion:nil ];
}

Solution

  • The call to animateUp is occurring before the ImageView has an initial frame set. You can defer this to viewDidAppear or viewDidLayoutSubviews and should see the animations occur correctly.

    -(void)viewDidLoad
    {
        [super viewDidLoad];
        [self.containerView addSubview:self.logoView = ({
            UIImageView *imageView = [UIImageView new];
            imageView.contentMode = UIViewContentModeScaleAspectFit;
            imageView.image = [UIImage imageNamed:@"thisImage"];
            imageView;
        })];
    }
    
    - (void) viewDidLayoutSubviews
    {
        [self animateUp];    // at this point the ImageView has its frame set
    }
    

    Please be aware that viewDidAppear and viewDidLayoutSubviews could get called multiple times in the lifetime of your UIViewController, so you'll want to accomodate for this should you only want the animation to occur once.