7

I have a UIImageView that is called upon programatically, I am trying to get it to spin around but its not working. The image will be placed inside a dynamic UITableView (I cannot change it to static). The image appears fine in my table view but it just doesn't spin.

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 122, 38, 38)];
    imageView.image = [UIImage imageNamed:@"settings1.png"];

    [self.view addSubview:imageView];

    CABasicAnimation *spin;
    spin = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    spin.fromValue = [NSNumber numberWithFloat:0];
    spin.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
    spin.duration = 4;
    spin.repeatCount = 10*1000;

    [imageView.layer addAnimation:spin forKey:@"360"];
Ed3121577
  • 510
  • 1
  • 6
  • 13

1 Answers1

14

It's probably because you're trying to start the animation in viewDidLoad. I'd suggest reorganizing your code in such a way that you create the image view instance in viewDidLoad, but then wait until viewDidAppear: is called to actually start the animation.

@property (strong, nonatomic) UIImageView *imageView;

And then

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 122, 38, 38)];
    self.imageView.image = [UIImage imageNamed:@"settings1.png"];

    [self.view addSubview:self.imageView];
}

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

    CABasicAnimation *spin = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    spin.fromValue = [NSNumber numberWithFloat:0];
    spin.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
    spin.duration = 4;
    spin.repeatCount = 10*1000;

    [self.imageView.layer addAnimation:spin forKey:@"360"];
}
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
  • Thanks! Such an easy solution, just for reference, why did this method work? is it because it waited until the viewDidLoad? – Ed3121577 Jun 09 '14 at 04:45
  • 4
    @user3121577 Basically, you should never try to start an animation until the view actually appears on screen. At the point where viewDidLoad gets called, the view controller's view has been loaded, but hasn't actually been added to the view hierarchy yet, so sometimes animations and things like that on the view, or its subviews can get thrown out, because they're happening too early in the life cycle. – Mick MacCallum Jun 09 '14 at 04:47