Wednesday, June 12, 2013

CATransaction setAnimationDuration example in Objective C (iOS).

CATransaction setAnimationDuration

Sets the animation duration used by all animations within this transaction group.

+ (void)setAnimationDuration:(CFTimeInterval)duration

Parameters
duration
An interval of time used as the duration.

Discussion of [CATransaction setAnimationDuration]
You can also set the animation duration for a specific transaction object by calling the setValue:forKey: method of that object and specifying the kCATransactionAnimationDuration key.

CATransaction setAnimationDuration example.
UIView *oldView = [[self subviews] objectAtIndex:0];
UIView *newView = [[self subviews] objectAtIndex:1];

[UIView beginAnimations:@"swapViews" context:nil];
[UIView setAnimationDuration:1];
    oldView.alpha = 0;
    newView.alpha = 1;
[UIView commitAnimations];

Example of [CATransaction setAnimationDuration].
[CATransaction begin];
[CATransaction setAnimationDuration:0.5];
[CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[CATransaction setCompletionBlock:^{
    NSLog(@"blabla");
}];

// Create the CABasicAnimation using your existing code
CABasicAnimation *myPropertyAnim = [CABasicAnimation animationWithKeyPath:@"myProperty"];
// TODO: Setup animation range
myPropertyAnim.toValue = newValue;

// The CATransaction does not observe arbitrary properties so this fails:
//myLayer.myProperty = newValue;

// Add the CAAnimation subclass during the CATransaction
[myLayer addAnimation:myPropertyAnim forKey:@"myKey"];

[CATransaction commit];

CATransaction setAnimationDuration example.
- (void)viewDidLoad {
    [super viewDidLoad];

    //Modifying base layer
    self.view.layer.backgroundColor = [UIColor orangeColor].CGColor;
    self.view.layer.cornerRadius = 20.0;
    self.view.layer.frame = CGRectInset(self.view.layer.frame, 20, 20);

    // Adding layer
    mylayer = [CALayer layer]; //mylayer declared in .h file
    mylayer.bounds = CGRectMake(0, 0, 100, 100);
    mylayer.position = CGPointMake(100, 100); //In parent coordinate
    mylayer.backgroundColor = [UIColor redColor].CGColor;
    mylayer.contents = (id)[UIImage imageNamed:@"glasses"].CGImage;   
    [self.view.layer addSublayer:mylayer];
}

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

    [CATransaction begin]; {
        [CATransaction setAnimationDuration:2];
        mylayer.position=CGPointMake(200.0,200.0);
        mylayer.zPosition=50.0;
        mylayer.opacity=0.5;
    } [CATransaction commit];
}

End of CATransaction setAnimationDuration example article.