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

匿名 (未验证) 提交于 2019-12-03 01:10:02

问题:

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

回答1:

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



回答2:

Frame: (X,Y,width,height).

Hence width and height wont change even wrt the super-super view. You can easily get the X, Y as following.

X = button.frame.origin.x + [button superview].frame.origin.x; Y = button.frame.origin.y + [button superview].frame.origin.y; 


回答3:

Updated for Swift 3

    if let frame = yourViewName.superview?.convert(yourViewName.frame, to: nil) {          print(frame)     } 



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