Search code examples
swiftxcodeuicollisionbehavior

Swift Xcode Collisions between group members, but not groups


I am in a single view application, and I've set up the colliding behavior. I have two different arrays or groups of UIViews. I want members of the same group to collide with one another, but members of differing groups to pass through one another. How can I do this?

collisions


Solution

  • If you simply have two arrays of views that you want to check collisions for, this should simply be a matter of testing all pairs between the two groups (or do you meant to find an optimized way of doing that?):

    let collidingViews = group1.filter{ (view) in group2.contains{ $0.frame.intersects(view.frame) }} 
    

    If you need to check collisions for a specific view that is part of the hierarchy, you could use the UIView tag as your group identifier and extend UIView to identify the collisions :

    extension UIView
    {
        func collidesWith(_ other: UIView)
        {
           return other !== self 
               && tag == other.tag
               && frame.intersects(other.frame)
        }
    
        var collidingViews:[UIView]
        { return superview.subviews.filter{self.collidesWith($0)} }
    }
    

    You can then check for collisions between one view (e.g. the one being moved) and the others using this function:

     for collidingView in view.collindingViews
     {
        // ... do something with the collindingView
     }