CGRectContainsPoint does not work on different views

心已入冬 提交于 2019-12-12 05:46:36

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/38957319/cgrectcontainspoint-does-not-work-on-different-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!