使用核心动画显式显示NSView

| 我正在尝试使用核心动画在ѭ0中滑动。我想我需要使用显式动画,而不是依赖诸如ѭ1之类的东西。这主要是因为我需要设置动画委托才能在动画完成后采取措施。 我使用动画器可以正常工作,但是正如我所说,动画结束时需要通知我。我的代码当前如下所示:
// Animate the controlView
NSRect viewRect = [controlView frame];
NSPoint startingPoint = viewRect.origin;
NSPoint endingPoint = startingPoint;
endingPoint.x += viewRect.size.width;
[[controlView layer] setPosition:NSPointToCGPoint(endingPoint)];

CABasicAnimation *controlPosAnim = [CABasicAnimation animationWithKeyPath:@\"position\"];
[controlPosAnim setFromValue:[NSValue valueWithPoint:startingPoint]];
[controlPosAnim setToValue:[NSValue valueWithPoint:endingPoint]];
[controlPosAnim setDelegate:self];
[[controlView layer] addAnimation:controlPosAnim forKey:@\"controlViewPosition\"];
这在视觉上是可行的(最后我得到通知),但是看起来实际的controlView并没有移动。如果我导致窗口刷新,则controlView消失。我尝试更换
[[controlView layer] setPosition:NSPointToCGPoint(endingPoint)];
[controlView setFrame:newFrame];
确实会导致视图(和图层)移动,但是它正在破坏某些东西,以至于我的应用不久后因段错误而死亡。 显式动画的大多数示例似乎只移动了
CALayer
。必须有一种移动ѭ0的方法,并且还可以设置一个委托。任何帮助,将不胜感激。     
已邀请:
我认为您需要在设置动画后最后调用setPosition。 另外,我不认为您应该明确地对视图层进行动画处理,而应使用动画器并设置动画来对视图本身进行动画处理。您也可以在动画师中使用委托:)
// create controlPosAnim
[controlView setAnimations:[NSDictionary dictionaryWithObjectsAndKeys:controlPosAnim, @\"frameOrigin\", nil]];
[[controlView animator] setFrame:newFrame];
    
对视图所做的更改在当前运行循环结束时生效。适用于图层的所有动画也是如此。 如果为视图的图层设置动画,则视图本身不受影响,这就是为什么在动画完成时视图似乎跳回到其原始位置的原因。 牢记这两点,可以通过将视图的帧设置为动画完成后想要的样子,然后在视图的图层中添加显式动画来获得所需的效果。 动画开始时,它将视图移动到起始位置,将其设置为动画到结束位置,动画完成后,视图将具有您指定的帧。
- (IBAction)animateTheView:(id)sender
{
    // Calculate start and end points.  
    NSPoint startPoint = theView.frame.origin;
    NSPoint endPoint = <Some other point>;    

    // We can set the frame here because the changes we make aren\'t actually
    // visible until this pass through the run loop is done.
    // Furthermore, this change to the view\'s frame won\'t be visible until
    // after the animation below is finished.
    NSRect frame = theView.frame;
    frame.origin = endPoint;
    theView.frame = frame;

    // Add explicit animation from start point to end point.
    // Again, the animation doesn\'t start immediately. It starts when this
    // pass through the run loop is done.
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@\"position\"];
    [animation setFromValue:[NSValue valueWithPoint:startPoint]];
    [animation setToValue:[NSValue valueWithPoint:endPoint]];
    // Set any other properties you want, such as the delegate.
    [theView.layer addAnimation:animation forKey:@\"position\"];
}
当然,要使此代码正常工作,您需要确保视图及其超级视图都具有层次。如果超级视图没有图层,则图形会损坏。     

要回复问题请先登录注册