检测UIView是否与其他UIView相交

时间:2011-09-09 12:38:11

标签: objective-c ios cocoa-touch uiview

屏幕上有一堆UIViews。我想知道什么是最好的方法来检查特定视图(我参考)是否与任何其他视图相交。我现在这样做的方法是,迭代所有子视图,并逐一检查框架之间是否有交叉点。

这看起来效率不高。有更好的方法吗?

4 个答案:

答案 0 :(得分:35)

有一个名为CGRectIntersectsRect的函数,它接收两个CGRect作为参数,如果两个给定的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;
}

答案 1 :(得分:3)

要根据接受的答案快速实现同样的事情,那么这里就是功能。现成的代码。只需按照步骤复制并使用它。顺便说一下,我使用Xcode 7.2和Swift 2.1.1。

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

感谢。

希望这会有所帮助。

答案 2 :(得分:0)

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

然后,可能在后台线程中,您可以使用数组中的内容运行一些碰撞测试。对于仅针对矩形的一些简单碰撞测试,请查看此SO问题:Simple Collision Algorithm for Rectangles

希望有所帮助!

答案 3 :(得分:0)

在我的情况下,视图是嵌套的,所以我做到了(既可以嵌套也可以不嵌套):

extension UIView {
    func overlaps(other view: UIView, in viewController: UIViewController) -> Bool {
        let frame = self.convert(self.bounds, to: viewController.view)
        let otherFrame = view.convert(view.bounds, to: viewController.view)
        return frame.intersects(otherFrame)
    }
}

希望有帮助。

相关问题