Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get position of UIView in respect to its superview's superview

I have a UIView, in which I have arranged UIButtons. I want to find the positions of those UIButtons.

I am aware that buttons.frame will give me the positions, but it will give me positions only with respect to its immediate superview.

Is there is any way we can find the positions of those buttons, withe respect to UIButtons superview's superview?

For instance, suppose there is UIView named "firstView".

Then, I have another UIView, "secondView". This "SecondView" is a subview of "firstView".

Then I have UIButton as a subview on the "secondView".

->UIViewController.view --->FirstView A ------->SecondView B ------------>Button 

Now, is there any way we can find the position of that UIButton, with respect to "firstView"?

like image 997
Shailesh Avatar asked Jul 10 '13 13:07

Shailesh


People also ask

What is a UIView?

UIView can be defined as an object by using which we can create and manage the rectangular area on the screen. We can have any number of views inside a view to create a hierarchical structure of the UIViews. The UIView is managed by using the methods and properties defined in the UIView class that inherits UIKit.


2 Answers

You can use this:

Objective-C

CGRect frame = [firstView convertRect:buttons.frame fromView:secondView]; 

Swift

let frame = firstView.convert(buttons.frame, from:secondView) 

Documentation reference:

https://developer.apple.com/documentation/uikit/uiview/1622498-convert

like image 146
mprivat Avatar answered Sep 24 '22 01:09

mprivat


Although not specific to the button in the hierarchy as asked I found this easier to visualize and understand:

From here: original source

enter image description here

ObjC:

CGPoint point = [subview1 convertPoint:subview2.frame.origin toView:viewController.view]; 

Swift:

let point = subview1.convert(subview2.frame.origin, to: viewControll.view) 
like image 32
Vlad Avatar answered Sep 26 '22 01:09

Vlad