How to get the frame of a view inside another view?
I guess you are looking for this method
// Swiftlet frame = imageView.convert(button.frame, to: self.view)// Objective-CCGRect frame = [imageView convertRect:button.frame toView:self.view];
There are four UIView
methods which can help you, converting CGPoints
and CGRects
from one UIView
coordinate reference to another:
– convertPoint:toView:– convertPoint:fromView:– convertRect:toView:– convertRect:fromView:
so you can try
CGRect f = [imageView convertRect:button.frame toView:self.view];
or
CGRect f = [self.view convertRect:button.frame fromView:imageView];
Swift 3
You can convert the button's frame to the view's coordinate system with this:
self.view.convert(myButton.frame, from: myButton.superview)
Make sure to put your logic inside viewDidLayoutSubviews
and not viewDidLoad
. Geometry related operations should be performed after subviews are laid out, otherwise they may not work properly.
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) }}
You can just reference myButton.superview
instead of myImageView
when converting the frame.
Here are more options for converting a CGPoint
or 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)
See the Apple Developer Docs for more on converting a CGPoint
or CGRect
.