View のローカル座標を取得する方法のメモです。
(iOS 5で試しています。)
2つのViewが重なっている場合に、1つめのView の座標は2つ目の座標に変換するとどこになるのか?というときは UIView のメソッド convertPoint というのを使えば取得できます。
こんな感じで 50×50 の四角を二枚(One, Two)用意して、
Oneの(50,50)の位置に、Twoの(10, 10)がくるようにViewを作ります。
One の Viewのメソッド convertPoint の
point に 50, 50
toView に Two
を設定して、10, 10 が取得できるかサンプルで試してみます。
サンプルコード
– (void)viewDidLoad
{
[superviewDidLoad];
// 2つ View を用意する 一つ目の右下と二つ目の左上が重なるように
UIView *one = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
one.backgroundColor = [UIColorgreenColor];
[self.view addSubview:one];
UIView *two = [[UIView alloc] initWithFrame:CGRectMake(90, 90, 50, 50)];
two.backgroundColor = [UIColoryellowColor];
[self.view addSubview:two];
// one の右下座標 (50, 50)が twoのどこになるか確認する
CGPoint point = [one convertPoint:CGPointMake(50.0, 50.0) toView:two];
NSLog(@”%f, %f”, point.x, point.y);
}
実行すると、ちゃんと2つ目のViewのローカル座標がとれました。
10.000000, 10.000000