Ios 使用convertRect获取子视图的窗口坐标问题

Ios 使用convertRect获取子视图的窗口坐标问题,ios,cocoa-touch,uiview,uiviewcontroller,Ios,Cocoa Touch,Uiview,Uiviewcontroller,从主视图控制器的视图显示 儿童的abs点2:{{150,170},{20,20} 我原以为是140140,20,20 为什么X多了10个,Y多了30个?您需要调用的是: [child2.superview convertRect:child2.frame-to-view:nil] 不是 [child2 convertRect:child2.frame-to-view:nil] 例如,您需要在包含要转换的帧的视图上调用convertRect: 然后,您可能会发现X==140和Y==160,如果se

从主视图控制器的视图显示

儿童的abs点2:{{150,170},{20,20}

我原以为是140140,20,20


为什么X多了10个,Y多了30个?

您需要调用的是:

[child2.superview convertRect:child2.frame-to-view:nil]

不是

[child2 convertRect:child2.frame-to-view:nil]

例如,您需要在包含要转换的帧的视图上调用convertRect:


然后,您可能会发现X==140和Y==160,如果self.view位于它下面的ui窗口中,那么额外的20 Y是状态栏。

您需要调用的是:

[child2.superview convertRect:child2.frame-to-view:nil]

不是

[child2 convertRect:child2.frame-to-view:nil]

例如,您需要在包含要转换的帧的视图上调用convertRect:


然后你可能会发现X==140和Y==160,如果self.view位于它下面的UIWindow中,那么额外的20 Y是状态栏。

我可以问一下为什么调用superview而不是视图本身吗?@Ted正如文档中所说-CGRectconvertRect:cgrectToView:UIView*视图-将一个矩形从接收者的坐标系转换为另一个视图的坐标系。而child2.frame是在其父视图的坐标系中定义的。我可以问一下为什么调用superview而不是视图本身吗?@Ted正如文档中所说-CGRectconvertRect:cgrectToView:UIView*视图-将一个矩形从接收者的坐标系转换为另一个视图的坐标系。而child2.frame是在其父视图的坐标系中定义的。
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] ));