views:

1011

answers:

2

I've created a new View-based Application in XCode.

In the ViewController, the only code that I've modified looks like this:

- (void)viewDidLoad {
[super viewDidLoad];

UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
newView.backgroundColor = [UIColor redColor];
[self.view addSubview:newView];


[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:0.5f] forKey:kCATransactionAnimationDuration];

newView.layer.frame = CGRectMake(20,20,220,220);

[CATransaction commit];
}

It should create a red square that animates for half a second as soon as the application loads. The problem is that it does not animate. I can't figure out why. I created this simple project to isolate all variables, and yet it still doesn't work.

Can anyone help out or point me in the right direction of some Core-Animation reading material. I've already gone through all of Apple's stuff.

A: 

Can anyone help out or point me in the right direction of some Core-Animation reading material. I've already gone through all of Apple's stuff.

See: Core Animation for Mac OS X and the iPhone: Creating Compelling Dynamic User Interfaces for an excellent walkthrough of Core Animation on views and layers.

Alex Reynolds
+1  A: 

Your code would animate as expected if you were setting properties on a CALayer (they animate by default). For UIViews to animate, you must change their properties within a block like the following:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0f];

// Change properties here

[UIView commitAnimations];

CATransactions are used to group animations so that they are coordinated, or manually disable animations for a group of objects.

Brad Larson
Isn't that what the line "newView.layer.frame = CGRectMake(20,20,220,220);" does? The 'layer' property accesses the CALayer of the UIView. That should animate it, correct?
mazniak
You're right, I misread that line. In that case, what you're doing should animate. It's a little cleaner to use the UIView begin / commit animations block, but it should work the same.
Brad Larson
What I think might be happening is that the run loop doesn't hit its end after you add the new subview, but before you trigger the animation. Therefore, it's just placing the view at its final position. Try moving the animation code to a separate method and trigger that method using performSelector:withObject:afterDelay: with a delay of 0.01 s. That should let the animation activate after the subview has been added.
Brad Larson
Ahhhhh, I'm dumb.Code in my delegate was rendering/animating the views before running [window addSubview:viewController.view];I can't believe I didn't notice that earlier.
mazniak