Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get location of an object relative to the Window in iOS?

How do we get the "visual" coordinates of an object? For example, getting the frame of a textfield within a UIScrollView will give me the X and Y relative to the UIScrollView, but I want to know the X and Y as if they were shown in the view.

Is there a built in function?

like image 947
Jonas Stawski Avatar asked Jan 30 '12 17:01

Jonas Stawski


3 Answers

Once you have the point as a CGPoint you can call:

// Objective-C
- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view

// C#'s UIView class contains this method:
PointF ConvertPointToView (PointF point, UIView target);

on you UIView.

pass in you point in your views co-ordinates as point. And for view pass in

// Objective-C
[UIWindow keyWindow]

// C#
UIWindow.KeyWindow

This will then return a CGPoint (PointF in C#) converted into the windows coordinate system!

So for example:

// Objective-C
CGPoint convertedPoint = [myScrollView convertPoint:textField.frame.origin 
                                             toView:[UIWindow keyWindow]];

// C#
var convertedPoint = myScrollView.ConvertPointToView (
     textField.Frame.Location, UIWindow.KeyWindow);

Hope this helps :)

like image 183
George Green Avatar answered Oct 05 '22 01:10

George Green


UIView has some convertPoint and convertRect functions:

  • - convertPoint:fromView: <--link to Apple doc
  • - convertPoint:toView:
  • – convertRect:toView:

etc.

like image 26
MechEthan Avatar answered Oct 05 '22 00:10

MechEthan


Might just be me, but wouldnt this work fine?

- (CGRect) convertView:(UIView*)view
{
    CGRect rect = view.frame;

    while(view.superview)
    {
        view = view.superview;
        rect.origin.x += view.frame.origin.x;
        rect.origin.y += view.frame.origin.y;
    }

    return rect;

}
like image 45
Kevin R Avatar answered Oct 05 '22 01:10

Kevin R