检测UIView是否与其他UIView相交

我在屏幕上有一堆UIViews。 我想知道什么是最好的方式来检查是否一个特定的视图(我参考)是相交任何其他意见。 我现在正在做的是,迭代所有的子视图,并逐个检查帧之间是否有交集。

这似乎不是很有效。 有一个更好的方法吗?

首先,创build一个数组来存储所有UIViews及其相关引用的帧。

然后,可能在后台线程中,可以使用数组中的内容运行一些碰撞testing。 对于一些简单的矩形碰撞testing,看看这个问题: 矩形的简单碰撞algorithm

希望有所帮助!

有一个名为CGRectIntersectsRect的函数,它接收两个CGRects作为参数,如果两个给定的rects相交,则返回。 和UIView有子视图属性是UIView对象的NSArray。 所以你可以写一个BOOL返回值的方法来遍历这个数组,并检查两个矩形是否相交,如下所示:

- (BOOL)viewIntersectsWithAnotherView:(UIView*)selectedView { NSArray *subViewsInView = [self.view subviews];// I assume self is a subclass // of UIViewController but the view can be //any UIView that'd act as a container //for all other views. for(UIView *theView in subViewsInView) { if (![selectedView isEqual:theView]) if(CGRectIntersectsRect(selectedView.frame, theView.frame)) return YES; } return NO; } 

要按照被接受的答案迅速实现同样的事情,那么这里就是函数。 现成的代码。 按照步骤复制和使用它。 顺便说一下,我使用Swift 2.1.1的Xcode 7.2。

 func checkViewIsInterSecting(viewToCheck: UIView) -> Bool{ let allSubViews = self.view!.subviews //Creating an array of all the subviews present in the superview. for viewS in allSubViews{ //Running the loop through the subviews array if (!(viewToCheck .isEqual(viewS))){ //Checking the view is equal to view to check or not if(CGRectIntersectsRect(viewToCheck.frame, viewS.frame)){ //Checking the view is intersecting with other or not return true //If intersected then return true } } } return false //If not intersected then return false } 

现在按照以下方式调用这个函数

 let viewInterSected = self.checkViewIsInterSecting(newTwoPersonTable) //It will give the bool value as true/false. Now use this as per your need 

谢谢。

希望这有助于。