CGRectContainsPoint 不适用于不同的视图 [英] CGRectContainsPoint does not work on different views

查看:38
本文介绍了CGRectContainsPoint 不适用于不同的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个简单的拖放项目.当我使用 CGRectContainsPoint 将视图拖放到不同的视图上时,它可以工作.但是两个视图应该在同一个视图中.现在假设我有一个名为A"的视图,它包含两个视图.一个 UIView 和一个 UIStackView.如果我将 Stack View 中的一个视图拖到 UIView 它不会下降.简单的 CGRectContainsPoint 不能用于从不同视图拖放.有什么办法可以解决吗?

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?

推荐答案

由于每个视图都有自己的坐标系,因此在比较它们之前必须将所有坐标转换为相同的坐标系(例如使用 CGRectContainsPoint.而且您需要了解每个点或矩形的坐标系.Apple 总是在文档中指定它.

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:

在 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
}

请注意,frame 指定了超级视图坐标系中的边界.因此,我将其更改为 bounds,它在视图的 onw 坐标系中指定它.此外,center 使用超级视图的坐标系.因此,我将点从超级视图的系统转换为参考视图的系统.

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.

这篇关于CGRectContainsPoint 不适用于不同的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆