2010-07-22 3 views
0

Код ниже обрабатывает стопку 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; 
    } 
} 

ответ

3

Вы довольно близко. Я бы просто изменить свой код в цикле к этому:

for(int i=0;i<[layerArray count]; i++) 
{ 
    CALayer *currentLayer = [layerArray objectAtIndex:i]; 

    CGPoint endPoint = CGPointMake(0, currentLayer.position.y + offset); 
    CGPoint currentPoint = [currentLayer position]; 

    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"]; 
    [anim setFromValue:[NSValue valueWithCGPoint:currentPoint]]; 
    [anim setToValue:[NSValue valueWithCGPoint:endPoint]]; 
    [anim setDelegate:self]; 
    [anim setDuration:1.0]; 

    [anim setValue:@"stackLayer" forKey:@"kind"]; 
    [anim setValue:[NSNumber numberWithInt:i] forKey:@"index"]; 

    [currentLayer setPosition:endPoint]; 
    [currentLayer addAnimation:anim forKey:@"position"]; 
} 

Это гарантирует, что ваш слой одушевляет от текущей позиции до позиции смещения, а также установить положение для слоя так, что он не вернется вернуться в исходное положение, когда анимация завершена - хотя вы не можете заставить ее работать правильно, если вы все это делаете в том же цикле запуска. Возможно, вам захочется настроить слои и добавить их, когда ваш просмотр загрузится, а затем оживить их как ответ на какое-либо другое действие или вызвав -performSelector: withObject: afterDelay передавая ему некоторую задержку, которая позволит ему получить в очереди для последующей итерации цикла выполнения.

+0

Это отлично работает! Благодаря! – carloe

-1

Вам необходимо установить новое положение слоя в анимации, а не непосредственно на слой.

CAlayer *layer = ... 

CABasicAnimation *positionAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation"];] 
positionAnimation.fromValue = oldPOsition 
positionAnimation.toValue = newPosition 
positionAnimation.duration = n; 
positionAnimation.delegate = self;   

[layerToAnimate addAnimation:layerAnimation forKey:@"transform.translation"] 
+0

Проблема в том, что то, что вы выделяете, является явной анимацией, и слой возвращается в исходное положение, когда анимация заканчивается. – carloe

 Смежные вопросы

  • Нет связанных вопросов^_^