Using Convertpoint to Get the Relative Position Inside a Parent Uiview

Using convertPoint to get the relative position inside a parent UIView

button.center is the center specified within the coordinate system of its superview, so I
assume that the following works:

CGPoint p = [button.superview convertPoint:button.center toView:self.view]

Or you compute the button's center in its own coordinate system and use that:

CGPoint buttonCenter = CGPointMake(button.bounds.origin.x + button.bounds.size.width/2,
button.bounds.origin.y + button.bounds.size.height/2);
CGPoint p = [button convertPoint:buttonCenter toView:self.view];

Swift 4+

let p = button.superview!.convert(button.center, to: self.view)

// or

let buttonCenter = CGPoint(x: button.bounds.midX, y: button.bounds.midY)
let p = button.convert(buttonCenter, to: self.view)

Get a UIView’s bounds relative to the window?

UIView *parent = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
UIView *child = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 10, 10)];
[parent addSubview:child];
[self.view addSubview:parent];
NSLog(NSStringFromCGRect([self.view convertRect:child.frame fromView:child.superview]));

Result in log:

{{60, 60}, {10, 10}}

iOS: How to determinie CGPoint of an object in scrollView

Add the contentOffset of the UIScrollView. This will adjust your point relative to the amount of scroll applied in the UIScrollView:

x = self.object.bounds.origin.x + self.yourScrollView.contentOffset.x;
y = self.object.bounds.origin.y + self.yourScrollView.contentOffset.y;

UIView absolute screen point

So I ended up using UITapGestureRecognizer instead and calculating the position like this:

    CGPoint gestureViewLocation = [gesture locationInView:gesture.view];
CGPoint absoluteLocation = [gesture locationInView:self.parentViewController.view];
CGRect fromRect = CGRectMake(absoluteLocation.x-gestureViewLocation.x, //subtract to we get point relative to gesture view
absoluteLocation.y-gestureViewLocation.y, //subtract to we get point relative to gesture view
gesture.view.frame.size.width,
gesture.view.frame.size.height);


Related Topics



Leave a reply



Submit