2011-10-03 28 views
0

我寫了下面的代碼:UIImageView定位問題?

-(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按鈕i停止然後卸載站立動畫。之後,我加載了跳轉動畫並開始用playerJumpRight函數在屏幕上移動它。

一切似乎好工作有兩個例外:

  1. 跳躍的動畫動作像沿x軸,但由於某種原因不 保持其原始y位置,這在上面的代碼是「234預期」。

  2. 當跳動動畫x位置符合if語句 一切工作像預期的站立動畫 新設立的職位是這樣要求過(84,242)希望的位置的

我一直在尋找了一段時間,嘗試了很多不同的解決方案,但在每一個嘗試失敗 。請在我剛開始編寫ios/objective c時請原諒我的新手。

我非常感謝您提供的任何幫助。

回答

1

如果從其超級視圖中刪除子視圖,那麼center屬性將變得毫無意義,因爲它引用了超級視圖的座標系。不要從超級視圖中刪除並重新添加aJumpRight,只需修改它的center屬性,這會移動我認爲是您所追求的視圖。

請注意,您也可以使用基於塊的動畫將動畫更改爲center,有關詳細信息,請參閱UIView類參考here

此外,您可能會混淆視圖的center與其frame.origin。後者是視圖的左上角。我不認爲設置center沒有superview的視圖有任何影響,但我不確定這一點。在這種情況下,你可以確定幀的來源。

+0

你是完全正確的,我是混淆與frame.origin中心。非常感謝你,我在過去兩天一直在努力解決這個問題。也謝謝你的提示,不要從超級視圖中刪除。我想如果我從超視圖中刪除它,並將其改爲中心,當我將它添加回來查看它將修復我正在定位的問題,但它確實是中心與幀起源的混淆。再次謝謝你。 – RickyTheCoder