CGRect在动画期间不会改变

时间:2011-08-13 19:32:51

标签: iphone objective-c ios cgrect

我正在为UIView设置动画,并想检查它的框架是否与另一个UIView的框架相交。这就是我“生成”其中一个UIViews的方法:

- (void) spawnOncomer 
{    
oncomer1 = [[Oncomer alloc] initWithType:@"car"];
    [self.view addSubview:oncomer1];


    //make the oncomer race across the screen
    [UIView beginAnimations:nil context:NULL]; {
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDuration:3.0];
        [UIView setAnimationDelegate:self];
        CGRect f = oncomer1.frame;
        f.origin.y = self.view.frame.size.height+oncomer1.frame.size.height;
        oncomer1.frame = f;
        [UIView setAnimationDidStopSelector:@selector(decountCar)];
    } 
    [UIView commitAnimations];
}

到目前为止一切顺利。现在我想检查这个UIView和我的其他UIView是否发生冲突:

- (void) checkCollision {

    bool collision = CGRectIntersectsRect(car.frame, oncomer1.frame);
    if (collision) {
        NSLog(@"BOOOOOOOM");
    } else {
        NSLog(@"Oncomer: %@", NSStringFromCGRect(oncomer1.frame));
    }

}

然而,他们永远不会发生碰撞。虽然我看到oncomer1在屏幕上移动,但loggin oncomer1.frame永远不会改变:它会一直输出Oncomer: {{50, 520}, {30, 60}}(这是动画后的值)。

有谁知道这是为什么?

P.S。这两种方法都是使用NSTimer直接或间接调用的,因此在后台执行

2 个答案:

答案 0 :(得分:3)

即使在动画块中,

UIView几何更新也会立即应用于CALayer。要获取应用了动画的图层版本,您可以使用-[CALayer presentationLayer],如下所示(警告 - 未经测试的代码):

- (void) checkCollision {
    CGRect oncomerFrame = oncomer1.layer.presentationLayer.frame;
    bool collision = CGRectIntersectsRect(car.frame, oncomerFrame);
    if (collision) {
        NSLog(@"BOOOOOOOM");
    } else {
        NSLog(@"Oncomer: %@", NSStringFromCGRect(oncomerFrame));
    }

}

答案 1 :(得分:0)

从你的代码:

CGRect f = oncomer1.frame;
f.origin.y = self.view.frame.size.height+oncomer1.frame.size.height;
oncomer1.frame = f;

框架永远不会改变的逻辑解释是,您只是更改框架的y,并且始终将其设置为由两个height确定的相同值。