Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CABasicAnimation not working with UIImageView

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"];
like image 528
Ed3121577 Avatar asked Jun 09 '14 03:06

Ed3121577


1 Answers

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"];
}
like image 62
Mick MacCallum Avatar answered Nov 19 '22 10:11

Mick MacCallum