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

时间:2011-11-10 16:06:17

标签: ios objective-c xcode uiimageview frame

我在UIImageView(主视图)中有self.view,其中有一个UIButton。我想知道UIButtonself.view的{​​{1}}的框架是什么,而不是UIImageView

4 个答案:

答案 0 :(得分:88)

我猜你正在寻找这种方法

– convertRect:toView:

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

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

答案 1 :(得分:19)

有四种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];

答案 2 :(得分:7)

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)

有关转换CGPointCGRect的详情,请参阅Apple Developer Docs

答案 3 :(得分:2)

这样的东西?可能是完全错误的,不要真的想通过; 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);

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