UIImageView定位问题?

时间:2011-10-03 09:30:10

标签: iphone

我写了以下代码:

-(void)viewDidLoad{
JumpVelocity = 10;

aStandRightArray = [[NSArray alloc] initWithObjects:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aStandR1" ofType:@"png"]],
                                                     [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aStandR2" ofType:@"png"]],
                                                     [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aStandR3" ofType:@"png"]],
                                                     [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aStandR2" ofType:@"png"]],   
                                                     nil];

aJumpRightArray = [[NSArray alloc] initWithObjects:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aJumpR" ofType:@"png"]], nil];

aStandRight = [[UIImageView alloc] initWithFrame:CGRectMake(0, 242, 55, 65)];
aStandRight.animationImages = aStandRightArray;
aStandRight.animationDuration = 0.5;
[self.view addSubview:aStandRight];

aJumpRight = [[UIImageView alloc] initWithFrame:CGRectMake(0, 234, 69, 65)];
aJumpRight.animationImages = aJumpRightArray;
[self.view addSubview:aJumpRight];}

-(IBAction)buttonJumpRight:(id)sender{
[aStandRight stopAnimating];
[aStandRight removeFromSuperview];
[aJumpRight startAnimating];

jumpTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(playerJumpRight) userInfo:nil repeats:YES];}

-(void)playerJumpRight{
[aJumpRight removeFromSuperview];
aJumpRight.center = CGPointMake(aJumpRight.center.x + JumpVelocity, 234);
[self.view addSubview:aJumpRight];

if(aJumpRight.center.x >= 84.0)
{
    [jumpTimer invalidate];
    jumpTimer = nil;
    [aJumpRight stopAnimating];
    aStandRight.center = CGPointMake(84, 242);
    [aStandRight startAnimating];
    [self.view addSubview:aStandRight];
}

}

基本上我在这里尝试做的是加载一个常设动画,然后当用户按下buttonJumpRight按钮时,我停止然后卸载常备动画。之后,我加载了跳转动画并开始使用playerJumpRight函数在屏幕上移动它。

一切似乎都运行正常,有两个例外:

  1. 跳跃动画沿着x轴预期移动,但由于某种原因没有 保持原来的y位置,在上面的代码中是“234”。

  2. 当跳转动画x位置满足if语句的要求时 一切都像预期的新创建的立场动画的位置 远离(84,242)的愿望位置。

  3. 我一直在寻找相当长的时间,尝试了许多不同的可能解决方案但失败了 每一次尝试。请原谅我的新手,因为我刚开始为ios / objective c编码。

    我非常感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:1)

如果从超级视图中删除子视图,则center属性变为无意义,因为它引用了超视图的坐标系。不要从超级视图中删除并重新添加aJumpRight,只需修改它的center属性,这将移动我认为您所追求的视图。

请注意,您也可以使用基于块的动画为center的更改设置动画,有关详细信息,请参阅UIView类参考here

此外,您可能会将center视图与frame.origin混淆。后者是视图的左上角。我不认为为没有超视图的视图设置center会有任何影响,尽管我不确定那个。在这种情况下,您绝对可以设置框架原点。