xcode 获取Objective C IPad App中任何控件的绝对位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6365404/
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-09-14 21:16:35  来源:igfitidea点击:

Get Absolute location of Any Control in Objective C IPad App

iphoneobjective-cxcodeipadlocation

提问by HackAndSlasher

Im wondering if there is anyway that you can get the absolute location of a control in a ipad/iphone application. e.g. I have a TextField which is within a child of a child of a view. I want to know the X and Y values in relation to the top Parent View (e.g. currently the x and Y of the textfield return 10 and 10 because that is it's frame location within its own view, but I want to know this in relation to its parent which should be something like X = 10 and Y = 220). I need to make a generic method for this somehow. Hope this make sense.

我想知道是否有任何方法可以获得 ipad/iphone 应用程序中控件的绝对位置。例如,我有一个位于视图子项的子项内的 TextField。我想知道与顶部父视图相关的 X 和 Y 值(例如,当前文本字段的 x 和 Y 返回 10 和 10,因为这是它自己视图中的框架位置,但我想知道这一点与它的父级应该类似于 X = 10 和 Y = 220)。我需要以某种方式为此制定一个通用方法。希望这是有道理的。

Any ideas?

有任何想法吗?

回答by Jeremy W. Sherman

You are looking for -[UIView convertPoint:toView:].

您正在寻找-[UIView convertPoint:toView:].

For example, to get the origin of a view viewin terms of its window's base coordinates, you would write:

例如,要view根据窗口的基坐标获取视图的原点,您可以编写:

CGPoint localPoint = [view bounds].origin;
CGPoint basePoint = [view convertPoint:localPoint toView:nil];

If you instead want to convert the point into the coordinate system of some other view within the same window, you can use that view as the toView:argument instead of nil:

如果您想将点转换为同一窗口内其他视图的坐标系,您可以使用该视图作为toView:参数而不是nil

NSAssert([view window] == [otherView window],
        @"%s: Views must be part of the same window.", __func__);
CGPoint otherPoint = [view convertPoint:localPoint toView:otherView];

Because different coordinate systems can have different scales, you might find -convertRect:toView:to be more useful, depending on what you're planning to do with the coordinates. There are also analogous -fromView:versions of both the point and rect conversion methods.

因为不同的坐标系可以有不同的比例,您可能会发现-convertRect:toView:更有用,这取决于您打算对坐标做什么。-fromView:点和矩形转换方法也有类似的版本。