Ali Alebrahim Ali Alebrahim - 4 months ago 15
Swift Question

View center according to its ViewcController - iOS Swift

I have a

UIView
inside another
UIView
.

What is the best way to get the inner
UIView
position according to the
ViewController
, and not to its
superView
?

func answerViewTapAction(sender: UITapGestureRecognizer) {
if let myViewIndex = returnActiveView() {
var choosenView: numberView!
print("view \(myViewIndex) will move to slot \(sender.view!.tag)")
for noView in noViews {
if noView.tag == myViewIndex {
choosenView = noView
}
}
//print(choosenView.center)
print(sender.view!.center)
UIView.animateWithDuration(0.7, animations: {
choosenView.center = CGPoint(
x: CGRectGetMidX(sender.view!.frame),
y: CGRectGetMidY(sender.view!.frame))
})
}else {
print("view will not move")
}

}


i want to access my sender.view center according to the ViewController not according to its superview

Answer

You want the convertPoint method of UIView. In particular the convertPoint(_ point: CGPoint, toView view: UIView?) -> CGPoint. Documentation here.

If you need an example let me know. You just need to call it once and pass the toView your superview of the view you're trying to figure out.

EDIT: to the example we go!

Let's consider three views: A, B and C. And a fancy ASCII art to go along.

(0, 0, 20, 20)
+----------------------------------+
| A                                |
|    (5, 5, 10, 10)                |
|    +--------------------+        |
|    |B                   |        |
|    |    (5, 5, 5, 5)    |        |
|    |    +-----------+   |        |
|    |    |C          |   |        |
|    |    |           |   |        |
|    |    |           |   |        |
|    |    |           |   |        |
|    |    |           |   |        |
|    |    |           |   |        |
|    |    |           |   |        |
|    |    +-----------+   |        |
|    |                    |        |
|    |                    |        |
|    +--------------------+        |
|                                  |
|                                  |
|                                  |
+----------------------------------+

View A is the ViewController.view and it's at X: 0, Y: 0, width: 20, and height: 20. View B is a subview of A and it's at X: 5, Y: 5, width: 10, height: 10 according to view A. View C is a subview of B and it's at X: 5, Y: 5, width: 5, height: 5 according to view B. But according to view A the C is actually at X: 10, Y: 10 because the view B is at 5, 5. So what we need to to to figure out the origin of view C according to view A is to convertPoint.

The way to do it:

let originOfC = B.convertPoint(C.frame.origin, toView: A)

And that's it. You can do the same thing programatically with a fiew loops but the example above is somewhat cleaner. Now I have given you an example for the origin. To get the center you can use the view.center property or add a half of the C width to x coordinate of originOfC and half of the height to y of originOfC.