简体   繁体   中英

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

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 (eg the one being moved) and the others using this function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM