下面的代碼處理一堆CALayers
。每次將新圖層推入堆疊時,該功能都會被鎖定,並且所有現有圖層都會在屏幕上向下移動,以便爲新圖層騰出空間。一旦最後一層完成動畫,該功能將再次解鎖,以便可以推送新圖層。CALayer試圖動畫時會立即移動?
我的問題是每次這段代碼在newLayer
上運行最初的動畫。換句話說,不是將新圖層放置在CGPointMake(0, 0-offset)
處,然後將其動畫到CGPointMake(0, currentLayer.position.y + offset)
,而是立即顯示在最後位置。我錯過了什麼嗎?謝謝!
-(void)addNewLayerWithHeight:(float)layerHeight {
if(!animationLocked) {
animationLocked = YES;
//Offset is the ammount that each existing layer will need to be moved down by
int offset = layerHeight;
//Create the new layer
CALayer *newLayer = [CALayer layer];
[newLayer setBounds:CGRectMake(0, 0, self.view.layer.bounds.size.width, layerHeight)];
[newLayer setAnchorPoint:CGPointMake(0, 0)];
[newLayer setPosition:CGPointMake(0, 0-offset)];
[newLayer setBackgroundColor:[[UIColor redColor] CGColor]];
//Add the new layer to the view's layer and to layerArray
[self.view.layer addSublayer:newLayer];
[layerArray insertObject:newLayer atIndex:0];
//loop through all layers and move them to their new position...
for(int i=0;i<[layerArray count]; i++) {
CALayer *currentLayer = [layerArray objectAtIndex:i];
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
[anim setValue:@"stackLayer" forKey:@"kind"];
[anim setValue:[NSNumber numberWithInt:i] forKey:@"index"];
[anim setDelegate:self];
[anim setDuration:1.0];
currentLayer.actions = [NSDictionary dictionaryWithObject:anim forKey:@"position"];
currentLayer.position = CGPointMake(0, currentLayer.position.y + offset);
}
}
}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
//Make sure the last layer finished animating...
if([[anim valueForKey:@"kind"] isEqual:@"stackLayer"] && [[anim valueForKey:@"index"] isEqual:[NSNumber numberWithInt:[layerArray count]-1]]) {
animationLocked = NO;
}
}
這很好用!謝謝! – carloe 2010-07-22 23:02:00