If there are multiple views stacked and you don't need (or want) to know any possible views between the views you are interested in, you could do this:
static func getConvertedPoint(_ targetView: UIView, baseView: UIView)->CGPoint{
var pnt = targetView.frame.origin
if nil == targetView.superview{
return pnt
}
var superView = targetView.superview
while superView != baseView{
pnt = superView!.convert(pnt, to: superView!.superview)
if nil == superView!.superview{
break
}else{
superView = superView!.superview
}
}
return superView!.convert(pnt, to: baseView)
}
where targetView
would be the Button, baseView
would be the ViewController.view
.
What this function is trying to do is the following:
If targetView
has no super view, it's current coordinate is returned.
If targetView's
super view is not the baseView (i.e. there are other views between the button and viewcontroller.view
), a converted coordinate is retrieved and passed to the next superview
.
It continues to do the same through the stack of views moving towards the baseView.
Once it reaches the baseView
, it does one last conversion and returns it.
Note: it doesn't handle a situation where targetView
is positioned under the baseView
.