如何在一个视图中获取另一个视图的框架?

52

我在self.view(主视图)中有一个UIImageView,里面有一个UIButton。 我想知道UIButtonself.view中的框架大小,而不是在UIImageView中的。

4个回答

109

我猜你正在寻找这个方法

- convertRect:toView:

// Swift
let frame = imageView.convert(button.frame, to: self.view)

// Objective-C
CGRect frame = [imageView convertRect:button.frame toView:self.view];

21

有四种UIView方法可以帮助您将一个UIView坐标系中的CGPointsCGRects转换为另一个UIView坐标系:

 convertPoint:toView:
 convertPoint:fromView:
 convertRect:toView:
 convertRect:fromView:

所以你可以尝试一下

CGRect f = [imageView convertRect:button.frame toView:self.view];
或者
CGRect f = [self.view convertRect:button.frame fromView:imageView];

12

Swift 3

你可以使用以下代码将按钮的框架转换为视图的坐标系:

self.view.convert(myButton.frame, from: myButton.superview)


请确保将逻辑放在viewDidLayoutSubviews中而不是viewDidLoad中。几何相关操作应该在子视图布局后执行,否则可能无法正常工作。

class ViewController: UIViewController {

    @IBOutlet weak var myImageView: UIImageView!
    @IBOutlet weak var myButton: UIButton!

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        let buttonFrame = self.view.convert(myButton.frame, from: myButton.superview)
    }
}

在转换框架时,您可以只引用myButton.superview而不是myImageView


这里有更多将CGPointCGRect转换的选项。

self.view.convert(point: CGPoint, from: UICoordinateSpace)
self.view.convert(point: CGPoint, from: UIView)             
self.view.convert(rect: CGRect, from: UICoordinateSpace)
self.view.convert(rect: CGRect, from: UIView)

self.view.convert(point: CGPoint, to: UICoordinateSpace)
self.view.convert(point: CGPoint, to: UIView)
self.view.convert(rect: CGRect, to: UICoordinateSpace)
self.view.convert(rect: CGRect, to: UIView)
请参阅Apple Developer Docs,了解有关转换CGPointCGRect的更多信息。

1

像这样的吗?可能完全错误,没有认真考虑; p

CGRect frame = CGRectMake((self.view.frame.origin.x-imageview.frame.origin.x) +btn.frame.origin.x,
                          (self.view.frame.origin.y.imageview.frame.origin.y)+btn.frame.origin.y,
                          btn.frame.size.width,
                          btn.frame.size.height);

我不知道是否有更简单的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接