从主视图 Controller 的 ViewDidAppear
UIView* parent = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
UIView* child1 = [[UIView alloc] initWithFrame:CGRectMake(30, 30, 60, 60)];
UIView* child2 = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 20, 20)];
[parent setBackgroundColor:[UIColor redColor]];
[child1 setBackgroundColor:[UIColor blackColor]];
[child2 setBackgroundColor:[UIColor greenColor]];
[child1 addSubview:child2];
[parent addSubview:child1];
[self.view addSubview:parent];
NSLog(@"Absolute coordinates of child2: %@",NSStringFromCGRect([child2 convertRect:child2.frame toView:nil] ));
child2 的绝对点:{{150, 170}, {20, 20}}
我原以为原点是 (140,140, 20,20)。
为什么
X
有额外的 10 个Y
为 30 ?
最佳答案
您需要调用的是:[child2.superview convertRect:child2.frame toView:nil]
不是 [child2 convertRect:child2.frame toView:nil]
IE。您需要调用convertRect:
在包含您要转换的框架的 View 上。
然后你可能会发现 X == 140 和 Y == 160,额外的 20 Y 是 状态栏 鉴于 self.view
生活在UIWindow
在它下面。
关于ios - 使用 convertRect 获取 subview 的窗口坐标问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16832191/