Adam G
Adam G

Reputation: 1188

Objective C - Custom UIView Class Init With Animation

I have a simple custom UIView class with an associated xib file, which contains an ImageView that I'd like to begin rotating when the view is initialied.

Below is my code for the UIView. Using a breakpoint I can confirm the code is called:

#import "PinWithTimeView.h"
#import "QuartzCore/QuartzCore.h"


@implementation PinWithTimeView

- (id)initWithCoder:(NSCoder *)aDecoder {

    self = [super initWithCoder:aDecoder];

    if (self) {

        CABasicAnimation *fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        fullRotation.fromValue = [NSNumber numberWithFloat:0];
        fullRotation.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
        fullRotation.duration = 6;
        fullRotation.repeatCount = 10;
        [self.rotateCircle.layer addAnimation:fullRotation forKey:@"360"];

    }

    return self;
}


@end

However when I initialize like so, the ImageView never rotates. Can someone tell me why?

PinWithTimeView *pinMarker = [[[NSBundle mainBundle] loadNibNamed:@"PinWithTimeView" owner:self options:nil] firstObject];

Upvotes: 0

Views: 317

Answers (2)

Adam G
Adam G

Reputation: 1188

I got this working by moving the animation block into layoutSubviews method. Thanks to Duncan for pointing me in the right direction, that the view wasn't part of the hierarcy yet in initWithCoder

Upvotes: 0

Duncan C
Duncan C

Reputation: 131398

I don't think you can animate a view/layer unless it's part of the view hierarchy. In init/initWithCoder it hasn't been added yet.

you might try implementing the UIView method didMoveToSuperview method instead.

Upvotes: 1

Related Questions