iOS - Get location of a view in a window?

僤鯓⒐⒋嵵緔 提交于 2019-11-27 12:19:58

问题


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


回答1:


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




回答2:


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

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



回答3:


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

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



回答4:


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



回答5:


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.




回答6:


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



回答7:


CGRect myFrame = self.superview.bounds;


来源:https://stackoverflow.com/questions/7028850/ios-get-location-of-a-view-in-a-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!