我在self.view
(主视图)中有一个UIImageView
,里面有一个UIButton
。 我想知道UIButton
在self.view
中的框架大小,而不是在UIImageView
中的。
我在self.view
(主视图)中有一个UIImageView
,里面有一个UIButton
。 我想知道UIButton
在self.view
中的框架大小,而不是在UIImageView
中的。
我猜你正在寻找这个方法
// Swift
let frame = imageView.convert(button.frame, to: self.view)
// Objective-C
CGRect frame = [imageView convertRect:button.frame toView:self.view];
有四种UIView
方法可以帮助您将一个UIView
坐标系中的CGPoints
和CGRects
转换为另一个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
你可以使用以下代码将按钮的框架转换为视图的坐标系:
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
。
这里有更多将CGPoint
或CGRect
转换的选项。
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,了解有关转换CGPoint
或CGRect
的更多信息。像这样的吗?可能完全错误,没有认真考虑; 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);
我不知道是否有更简单的方法。