2015-10-20 58 views
0

我使用兩個UIImageViews,我已經添加到每個UIImageView的子視圖(UIView)。我使用CGRectIntersectsRect來檢測碰撞,但不起作用。所以,我有:CGRectIntersects子視圖的摘要

這是第一次的UIImageView

hand = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 13.5, 176)]; 
[hand setImage:[UIImage imageNamed:@"hand0.png"]]; 
[hand setContentMode:UIViewContentModeScaleAspectFit]; 

/// Add SUBVIEW which needs to be detected for collision 
hView = [[UIView alloc]initWithFrame:CGRectMake(3, 12, 7, 10)]; 
[hView setBackgroundColor:[UIColor redColor]]; 
[hand addSubview:hView]; 
[hand bringSubviewToFront:hView]; 

hand.center = self.view.center; 
[self.view addSubview:hand]; 

這裏是第二的UIImageView

ball = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 33.5, 176)]; 
[ball setImage:[UIImage imageNamed:@"ball0.png"]]; 
[ball setContentMode:UIViewContentModeScaleAspectFit]; 

/// Add SUBVIEW to detect for collision 
bView = [[UIView alloc]initWithFrame:CGRectMake(3, 155, 28, 10)]; 
[bView setBackgroundColor:[UIColor greenColor]]; 
[ball addSubview:bView]; 
[ball bringSubviewToFront:bView]; 

ball.center = self.view.center; 
[self.view addSubview:ball]; 

這裏是我的碰撞檢測,那裏每第二個代碼。

- (void)checkCollision 
{ 
    if (CGRectIntersectsRect(bView.frame, hView.frame)) { 
     //do something here 
    } 
} 

任何想法爲什麼它不檢測碰撞?我唯一想到的是因爲hView和bView是UIImageView的子視圖。

回答

1

問題是,bViewhView的幀是相對於它們各自的超級瀏覽。你需要將它們的幀轉換爲一個共同的祖先,以便它們能夠被正確比較。視圖控制器的視圖將是一個很好的候選人。

- (void)checkCollision { 
    CGRect hFrame = [hView convertRect:hView.bounds toView:self.view]; 
    CGRect bFrame = [bView convertRect:bView.bounds toView:self.view]; 

    if (CGRectIntersectsRect(bFrame, hFrame)) { 
     //do something here 
    } 
} 
+0

非常感謝你 –