2013-07-10 80 views
53

我有一个UIView,我在其中安排了UIButtons。我想找到那些UIButtons的位置。获取UIView相对于其superview的超级视图的位置

我知道,buttons.frame会给我的立场,但它只会给我立场就其直接superview。

是否有任何方法可以找到这些按钮的位置,就UIButtons superview的超级视图而言?

例如,假设有一个名为“firstView”的UIView。

然后,我有另一个UIView,“secondView”。这个“SecondView”是“firstView”的子视图。

然后我有UIButton作为“secondView”的子视图。

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

现在,有没有什么办法可以找到UIButton相对于“firstView”的位置?

回答

125

您可以使用此:

目标C

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

斯威夫特

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

文档参考:

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

+0

要添加到这一点,如果你的观点并不总是在同一视图(比方说,如果你在使用本函数),你可以把'... fromView:[按钮超级视图]];' – mylogon

6

框架:(X,Y,宽度,高度)。

因此,宽度和高度不会改变甚至超超级视图。您可以轻松获得X,Y,如下所示。

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

但是为什么我得到的X,Y值如此之高,就像我的X为0,0时那样我的代码行数越来越多; 180224左右? – YumYumYum

4

更新了斯威夫特3

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

     print(frame) 
    } 

enter image description here

相关问题