UIViewが他のViewと干渉していないか確認する方法のメモ
(iOS5 で試しています。)
collision detectionとかで何回も検索した記憶があるので、
簡単なゲームとかで便利なのかも。
ポイントとなるもの
・CGRectIntersectsRect ( CGRect rect1, CGRect rect2 )
→ CGRect が重なっていたら true
赤、黄、青の UIView を使ってサンプルを作ってみます。
赤と黄が重なるようにしてみました。
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
// A
UIView *red = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 20, 20)];
red.backgroundColor = [UIColor redColor];
[self.view addSubview:red];
// B
UIView *yellow = [[UIView alloc] initWithFrame:CGRectMake(25, 25, 20, 20)];
yellow.backgroundColor = [UIColor yellowColor];
[self.view addSubview:yellow];
// C
UIView *blue = [[UIView alloc] initWithFrame:CGRectMake(45, 45, 20, 20)];
blue.backgroundColor = [UIColor blueColor];
[self.view addSubview:blue];
// A と B
if(CGRectIntersectsRect(red.frame, yellow.frame)){
NSLog(@”AとBは重なっている。“);
}
// A と C
if(CGRectIntersectsRect(red.frame, blue.frame)){
NSLog(@”AとCは重なっている。“);
}
// B と C
if(CGRectIntersectsRect(yellow.frame, blue.frame)){
NSLog(@”BとCは重なっている。“);
}
}
@end
実行すると、
AとBは重なっている。
というログが出力されます。