1

Using Xcode Version 7.2.1 (7C1002), SDK iOS 9.2

Trying to animate imageView from left(offscreen) to right and have the animation repeat. I know the animation works as desired in viewDidLoad, but it's not ideal since the animation stops when a new controller is presented or the app has gone to the background and back to the foreground. I would like the animation to restart when the controller appears again. When I move the code to viewwillappear, the animation never happens.

I've tried:

  1. adding performSelector with a delay of 3 seconds -> doesn't animate
  2. wrapping the animateWithDuration in dispatch_async(dispatch_get_main_queue(), ^{ ... }); -> doesn't animate
  3. override viewDidLayoutSubviews method and call animation code from there -> doesn't animate

the only time the animation works is when called from viewDidLoad. Any help would be appreciated. I must be missing something really obvious. here's the code (which doesn't work)...

MainViewController.h

@property (nonatomic, strong) IBOutlet UIImageView *movingL2R_1_ImageView;
@property (nonatomic) IBOutlet NSLayoutConstraint  *movingL2R_1_LeadingConstraint;

MainViewController.m

- (void)viewDidAppear:(BOOL)animated {
   [super viewDidAppear:animated];
   [self startAnimations];
}

-(void) startAnimations{
   [self animateMovingL2R_1_ImageView];
   // other animations will go here...
}

-(void) animateMovingL2R_1_ImageView {

   NSTimeInterval animateInterval = 15;

   [UIView animateWithDuration:animateInterval delay:0 options:UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionRepeat animations:^{

        self.movingL2R_1_LeadingConstraint.constant = 500;
        [self.movingL2R_1_ImageView layoutIfNeeded];

    } completion:^(BOOL finished) {
        // back to original position
        self.movingL2R_1_LeadingConstraint.constant = -100;
    }];
}

NOTE: the movingL2R_1_LeadingConstraint is set to -100 in Interface Builder so that is where it starts.

storyboard entry point --> MainController

tdios
  • 225
  • 1
  • 2
  • 16
  • When you say it works when called from `viewDidLoad`, do you really mean `viewDidAppear`? Because that's what I see in your code that you posted. – Gavin Apr 06 '16 at 14:47
  • it should work in viewDidAppear but not in viewDidLoad – Teja Nandamuri Apr 06 '16 at 14:50
  • @Gavin - Sorry, to clarify I posted the code that does not work. the animation works when calling [self startAnimations] in viewDidLoad (commenting out the call in viewDidAppear, of course) – tdios Apr 06 '16 at 15:02

1 Answers1

2

As stated, the code above works perfectly if [self startAnimations]; is called in viewDidLoad, but not in viewDidAppear, but this answer helped me discover the subtle issue.

To get it working in viewDidAppear I needed to replace

[self.movingL2R_1_ImageView layoutIfNeeded];

with

[self.view layoutIfNeeded];

all is right with the world again.

Community
  • 1
  • 1
tdios
  • 225
  • 1
  • 2
  • 16