How to get the frame of a view inside another view?
I guess you are looking for this method
– convertRect:toView:
// Swift
let frame = imageView.convert(button.frame, to: self.view)
// Objective-C
CGRect 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
.
Something like this? might be totally wrong, dint really thinkt it through ;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);
I don't know if theres any easier way.