ios - 使用 convertRect 获取 subview 的窗口坐标问题

标签 ios cocoa-touch uiview uiviewcontroller

从主视图 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/

相关文章:

iOS:如何重用从 Nib 构建的 UIView?

ios - 向上滚动 UICollectionView 不要将 UIView 移到其上方

ios - :(id)sender有什么区别?

objective-c - objective-c - 获取协议(protocol)的父级列表

ios - 将 max float 用于 boundingRectWithSize 的高度是否有效

iphone - 我无法理解 - (void)playInputClick;

ios - 以编程方式向 UIView 添加约束

iOS 7 - 我可以更改 UITableViewCell 中的删除按钮背景颜色吗?

应用程序启动崩溃的 iOS BugSense 堆栈跟踪

iphone - 使用 cocos2d 在 iPhone 上显示游戏分数的最佳方式?