iOS - Get location of a view in a window?

aryaxt picture aryaxt · Aug 11, 2011 · Viewed 44k times · Source

I have a UIView that displays a popup after it's been clicked. The popup needs to be added to the main UIWindow to make sure that it goes on top of everything else.

I want the position of this popup to be relative to my UIView, so I need to know the relative location of my UIView in the window.

Question: How can I find the location of a UIView in a UIWindow when the UIView is not directly in the UIWindow (It's inside the view of my viewController)?

Answer

Magic Bullet Dave picture Magic Bullet Dave · Aug 11, 2011

Use can use the UIView method covertRect:toView to convert to the new co-ordinate space. I did something very similar:

// Convert the co-ordinates of the view into the window co-ordinate space
CGRect newFrame = [self convertRect:self.bounds toView:nil];

// Add this view to the main window
[self.window addSubview:self];
self.frame = newFrame;

In my example, self is a view that is being removed from its superView and added to the window over the top of where it was. The nil parameter in the toView: means use the window rather than a specific view.

Hope this helps,

Dave