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

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

我想你正在寻找这种方法

– convertRect:toView:

 // Swift let frame = imageView.convert(button.frame, to: self.view) // Objective-C CGRect frame = [imageView convertRect:button.frame toView:self.view]; 

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

Swift 3

你可以用下面的命令将button的框架转换为视图的坐标系:

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 。

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

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