Kənan Məmmədov Kənan Məmmədov - 1 year ago 138
iOS Question

CGRectContainsPoint does not work on different views

I am making a simple drag drop project. When I use CGRectContainsPoint to drag a view and drop on different view it works. But both of the view should be in a same view. Now let's say I have a view called "A" and it contains two views. One UIView and one UIStackView. If I drag a view inside of Stack View to UIView it does not drop. Simply CGRectContainsPoint does not work for dragging and dropping from different views. Is there any way to solve it?

Answer Source

As each view has it's own coordinate system, you have to convert all coordinates to the same coordinate system before you compare them (e.g. with CGRectContainsPoint. And you need to understand for each point or rectangle, in what coordinate system it is given. Apple always specifies it in the documentation.

As the common coordinate system either choose the one of a common parent or of the windows.

In your case, you compare whether the center of the view lies within the boundaries of another view. So pick a common parent view as the reference coordinate system, e.g. the view controllers main view:

In Swift:

let referenceView = self.view // assuming self is the view controller
let dropArea = referenceView.convertRect(self.dropAreaView1.bounds, fromView: self.dropAreaView1)
let center = referenceView.convertPoint(sender.view!.center, fromView: sender.view!.superview)
if CGRectContainsPoint(dropArea, center) {
   // do something

Note that frame specifies the boundary in the super view's coordinate system. Therefore, I've changed it to bounds, which specifies it in the view's onw coordinate system. Furthermore, center uses the super view's coordinate system. Therefore, I convert the point from the super view's to the reference view's system.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download