Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Absolute location of Any Control in Objective C IPad App

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.

Any ideas?

like image 294
HackAndSlasher Avatar asked Jun 15 '11 22:06

HackAndSlasher


1 Answers

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

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

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:

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.

like image 74
Jeremy W. Sherman Avatar answered Sep 18 '22 13:09

Jeremy W. Sherman