2011-06-28 22 views
0

我有與圖像「ImageView的」一種方法:碰撞兩個圖像的,與所述宣言問題

- (void)createNewImageView { 
// Get the view's frame to make it easier later on 


UIImage *image = [UIImage imageNamed:@"abouffer_03.png"]; 
UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 


// Add it at a random point 
[imageView setCenter:[self randomPointSquare]]; 
[[self view] addSubview:imageView]; 


// Animate it into place 
[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDuration:8.0f]; 
[imageView setCenter:CGPointMake(240, 160)]; 
[UIView commitAnimations]; 
[imageView release]; 

} 

和另一圖像「viewToRotate」(IBOuutlet在h和界面生成器定義)

而且我想用這種方法來檢查碰撞:

- (void)myRunloop 
{ 
// check collision 

if(CGRectIntersectsRect(imageView.frame, viewToRotate.frame)) 
{ 
    viewToRotate.alpha=0.2; 
} 
} 

但Xcode中總是給我的錯誤:「未申報的ImageView」,我不知道如何解決這個問題。我不想在這種方法中再次定義它。

回答

0

我just'd經歷過類似的問題其實當您設置的ImageView的框架上線

[imageView setCenter:CGPointMake(240, 160)]; 

的ImageView的獲取在內存裏解決,這只是由於動畫塊是它顯示你個e轉換imageView被移動到目的地,但實際上視圖的座標被賦予了目標位置,您可以通過在代碼行之後記錄座標來確認它。如果你真的需要以類似的方式做到這一點,你可以使用計時器而不是動畫塊,併爲自己設置動畫。但我通過使用animationDelegate來繞過這個問題。只需將動畫委託設置爲自定義並定義animationDidStopSelector即可。當動畫結束時,animationDidstopSelector會被觸發,因此對象到達它的最終目的地,或者你可以說有一個碰撞(在UI上)。希望幫助
下面是一個代碼示例:

- (void)createNewImageView { 
// Get the view's frame to make it easier later on 


UIImage *image = [UIImage imageNamed:@"abouffer_03.png"]; 
UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 


// Add it at a random point 
[imageView setCenter:[self randomPointSquare]]; 
[[self view] addSubview:imageView]; 


// Animate it into place 
[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDelegate:self]; 
[UIView setAnimationDidStopSelector:@selector(animationDidStop:)]; 
[UIView setAnimationDuration:8.0f]; 
[imageView setCenter:CGPointMake(240, 160)]; 
[UIView commitAnimations]; 
[imageView release]; 

} 

您animationDidStopSelector將成爲像:

-(void)animationDidStop:(id)sender { 
     //This is almost similar to collision detection, you can do something here 
} 
+0

坦克你,但你可以給我一個示例代碼或類似的東西,因爲我認爲我將無法做到你說的:/ –

+0

我可以定義什麼animationDidStopSelector –

+0

@jean mayot,對不起有點卡住了東西。我只是添加了一些示例代碼...希望能幫上忙 – Ahmed

0

在接口(.h文件中)宣佈這樣

UIImageView *imageView; 

,並在您createNewImageView() method.Use的

imageView = [[UIImageView alloc] initWithImage:image]; 
+0

謝謝你,但現在我遇到了另一個問題,當「ImageView的」出現在屏幕上不碰撞「viewToRotate」的碰撞方法被調用,我不知道爲什麼? –

0

imageView是一個局部變量的函數createNewImageView,因此不能被訪問通過myRunloop

如果您已宣佈imageView作爲IBOutlet 你可以這樣設置

UIImage *image = [UIImage imageNamed:@"abouffer_03.png"]; 
imageView.image = image 
+0

謝謝,但現在我遇到了另一個問題,當「imageView」出現在屏幕上而沒有與「viewToRotate」碰撞時調用碰撞方法,我不知道爲什麼? –

0

的圖像可以在其他方法後分配標籤圖像視圖,這樣你可以找到它:

[imageView setTag:1]; 

// in myRunloop 
UIImageView* imageView = [[self view] viewWithTag:1]; 
+0

現在我遇到了另一個問題,當「imageView」出現在屏幕上而沒有與「viewToRotate」碰撞的方法被調用時,我不知道爲什麼? –