aryaxt
aryaxt

Reputation: 77596

iOS - Get location of a view in a window?

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)?

Upvotes: 35

Views: 46923

Answers (8)

AKIL KUMAR
AKIL KUMAR

Reputation: 307

extension UIView {
    var globalFrame: CGRect {
        return convert(bounds, to: window)
    }
}

Upvotes: 0

WantToKnow
WantToKnow

Reputation: 1797

Swift 5 utility

extension UIView {
    var originOnWindow: CGPoint { return convert(CGPoint.zero, to: nil) }
}

Usage

let positionOnWindow = view.originOnWindow

For UIScrollView it is slightly different

extension UIScrollView {
    var originOnWindow: CGPoint { return convert(contentOffset, to: nil) }
}

Upvotes: 3

soan saini
soan saini

Reputation: 260

Below Xamarin.iOS Implementation Worked For Me.

    CGRect GetRectAsPerWindow(UIView view)
    {
        var window = UIApplication.SharedApplication.KeyWindow;
        return view.Superview.ConvertRectToView(view.Frame, window);
    }

Pass in the view whose frame you want with respect to Window.

Upvotes: 1

Yunus Nedim Mehel
Yunus Nedim Mehel

Reputation: 12369

You can ask your .superview to convert your origin for you for you

CGPoint originGlobal = [myView.superview convertPoint:myView.frame.origin 
                                               toView:nil];

Upvotes: 15

Stoyan Berov
Stoyan Berov

Reputation: 1371

I needed to do this in Xamarin.iOS

For anyone looking for a solution there, what eventually worked for me was:

CGRect globalRect = smallView.ConvertRectToView(smallView.Bounds, rootView);

Upvotes: 7

Craig
Craig

Reputation: 3297

Does UIView's convertPoint:toView: not work? So:

CGPoint windowPoint = [myView convertPoint:myView.bounds.origin toView:myWindow];

Upvotes: 8

Magic Bullet Dave
Magic Bullet Dave

Reputation: 9076

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

Upvotes: 69

ader
ader

Reputation: 5393

CGRect myFrame = self.superview.bounds;

Upvotes: -8

Related Questions