Question

I have a custom view (a small indicator derived from UIView with a rotation animation) which has basically a heart icon (UIImageView) on middle and a few balls (another UIImageView) rotating around it using layer animation. Here is my code:

-(void)performInitialization{
    self.backgroundColor = [UIColor clearColor];
    CGRect frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
    [imageView setImage:[UIImage imageNamed:@"RedHeart"]];
    balls = [[UIImageView alloc] initWithFrame:frame];
    [balls setImage:[UIImage imageNamed:@"AngularBalls"]];
    [self addSubview:imageView];
    [self addSubview:balls];

    [balls.layer beginRotating];
}

...where my category on CALayer has:

-(void)beginRotatingWithAngularVelocity:(float)velocity{
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    rotationAnimation.fillMode = kCAFillModeForwards;
    rotationAnimation.removedOnCompletion = YES;
    rotationAnimation.repeatCount = 999999;
    rotationAnimation.duration = velocity;
    rotationAnimation.cumulative = YES;
    rotationAnimation.fromValue = [NSNumber numberWithFloat:0];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2];
    [self addAnimation:rotationAnimation forKey:ROTATION_KEY];
}

-(void)beginRotating{
    [self beginRotatingWithAngularVelocity:0.7];
}

performInitialization is called in the init[WithFrame|WithCoder] method of my view. I have one of these views in my storyboard's main view and the view animates perfectly. If I put several instances of my custom view into that main view, they all animate perfectly too. There is no problem if I put my view into any view on that storyboard. However, when I put that same view into a view from a nib, it won't animate. The same code, the same settings in IB (copy pasted to make sure everything is the same), but the view is still, stuck on the initial view as if there was no animation attached to the layer). Why would that happen? How can I make that animation work on nibs?

UPDATE: The problem appears to be related to having the animation on view's initializer. In some occasions, I am animating right inside initialization, but sometimes, after it is loaded (e.g. user clicked something and something is downloading). The problem appears to be consistent with the former case. My previous fallacy about being about storyboard vs. nibs apparently is just coincidence. I've updated the title accordingly.

Was it helpful?

Solution

Initialization is too early. You need to wait until the view is in your interface (signaled to the view by didMoveToWindow. Until then, the view is not part of the rendering tree (which is what does the drawing/animation of its layers).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top