ios 如何将子视图的框架坐标系转换为自身视图的坐标系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11696508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:28:49  来源:igfitidea点击:

How to convert SubView's Frame Coordinate System to Self View's Coordinate System

iphoneobjective-cios

提问by rcmstark

I create programmatically one scrollView and some buttons inside there. When I click the any button have to show a popover.

我以编程方式创建了一个滚动视图和其中的一些按钮。当我单击任何按钮时,必须显示一个弹出窗口。

My button's origin in self.view is like (100,11) and inside scrollView (9,11) and scrowView is in somewhere in self.view. The popover shows in (9,11) but right one would be (100,11). I try use convert without success.

我的按钮在 self.view 中的原点类似于 (100,11) 和内部 scrollView (9,11) 并且 scrowView 位于 self.view 中的某个地方。弹出框显示在 (9,11) 中,但正确的是 (100,11)。我尝试使用 convert 没有成功。

-(IBAction)showPopover:(id)sender{
//... implemented popover above

//Wrong Origin:
NSLog(@"wrong x:%f y:%f",[sender frame].origin.x, [sender frame].origin.y);

//Transform to correct
CGRect frame = [self.view convertRect:[sender frame] toView:nil];

//Shoulf be right, but is not...
NSLog(@"new x:%f y:%f",frame.origin.x, frame.origin.y);
}

Anyone cam help me?

有人帮我吗?

回答by Nikolai Ruhe

A view's frame is already in the superview's coordinate system. So if your setup is self.viewcontains scrollviewcontains sender:

视图的框架已经在父视图的坐标系中。因此,如果您的设置self.view包含scrollviewcontains sender

CGRect frame = [sender.superview convertRect:sender.frame toView:self.view];

// or, better:

CGRect frame = [sender convertRect:sender.bounds toView:self.view];

回答by Hemang

Swift:

迅速:

let frame = sender.convert(sender.bounds, to: self.view)