关于 iphone:移动对象和设置新坐标中的错误修复

Bug Fixing in moving an object and setting new coordinates

我有一个非常简单的问题,但我找不到这个错误的原因。任何想法表示赞赏。

所以,我有一个 UIImageView 对象并将其从 A(x1,y1) 点轻弹(移动)到 B(x2,y2) 点到 C(x2,y2) 点,依此类推。 ..

当我将它从 A 移动到 B 到 C 到 D 等等......没有动画,它可以工作!

当我将它从 A 移动到 B 到 C .... 等等... 动画 -> 有一个错误!只有 A 到 B 有效,B 到 C,……等等出现在其他地方。

我基本上实现了 touchesBegan 方法和 touchesEnd 方法并使用

将对象移动到新位置

1
2
3
4
5
6
7
8
9
10
11
//NO ANIMATION  ==> Works !

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"End of touch");

    UITouch *touch = [[event touchesForView:self.view] anyObject];
    CGPoint location = [touch locationInView:touch.view];

    object.center = CGPointMake(location.x,  location.y);

}

..

1
2
3
4
5
6
7
8
9
10
11
//ADDING ANIMATION ==> Bug !

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"End of touch");

    UITouch *touch = [[event touchesForView:self.view] anyObject];
    CGPoint location = [touch locationInView:touch.view];

    [self spinLayer:object.layer duration:1 direction:SPIN_CLOCK_WISE newFrame:location];
    tempFrame = location;   // tempFrame is global.
}

在动画结束时,我做

1
2
3
4
5
6
7
8
9
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {

object.center = tempFrame;

// I assign this because the object has to be updated to its new location to move it to points B, C, D and so forth...

// The object is actually at the desired point. But it appears on the SCREEN at a different location although it `NSLogs` at the right point.

}

这是错误:

当我分配 object.center = tempFrame; 时,我希望对象位于 (x2,y2)。它在技术上位于 (x2,y2) (当我 NSlog 发现该位置时),但它出现在屏幕上的其他位置。

如果我再次将它移动到 C 点,它会使用 (x2, y2) 并正确移动到 (x3,y3),但它会再次出现在屏幕上的其他位置!

有什么想法吗??????


我建议使用 position.xposition.y 键路径,而不是使用动画 transform.translation.xtransform.translation.y 键路径。
所以,改变片段

1
2
3
4
theAnimationX=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
theAnimationX.toValue=[NSNumber numberWithFloat:(newFrame.x-object.center.x)];
theAnimationY=[CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
theAnimationY.toValue=[NSNumber numberWithFloat:(newFrame.y-object.center.y)];

1
2
3
4
theAnimationX=[CABasicAnimation animationWithKeyPath:@"position.x"];
theAnimationX.toValue=[NSNumber numberWithFloat:newFrame.x)];
theAnimationY=[CABasicAnimation animationWithKeyPath:@"position.y"];
theAnimationY.toValue=[NSNumber numberWithFloat:(newFrame.y)];

在这种情况下,您也可以只使用 position 键路径(并将 CGPoint 设置为 toValue)