Search code examples
objective-cuiscrollviewpositioncgrect

How to check "global" position of object in ios


I've got instance taskView of class which is sublcass of UIView. This instance is in UIScrollView which is at position (0, 50) and this UIScrollView is in self.view. The question is: how to check taskView position of screen? I want to check global position of this element. Elements like taskView are one or many in UIScrollView.


Solution

  • You can convert coordinates between views using these methods:

    So to convert a view's frame to be relative to some higher-up parent view, you could use this code:

    UIView *someParentView;
    UIView *childView;
    
    CGRect frameRelativeToParent = [childView convertRect:childView.bounds
                                                   toView:someParentView];
    

    Both views need to be part of the same view hierarchy (i.e. they need to exist inside the same window).

    If you specify nil for the second argument to these methods, you will be dealing with base window coordinates.

    There are also corresponding methods on UIWindow (e.g. convertRect:toWindow:) for converting coordinates between windows. When you specify nil for the second argument here, you are dealing with screen coordinates. One place you need to deal with screen coordinates is when you handle keyboard notifications. The keyboard's frame is given to you in screen coordinates so you have to use these methods to convert back to window coordinates before they are of any use.