iosswiftuikit-dynamicsuidynamicbehavior

UIKit dynamic behavior pan with attachment not continuing collision behavior?


How do I have collision detection occur on the pan of a UIDynamicItem?

Background: I'm generating 20 labels randomly from a set of colors/strings (this part is not essential to the question), and then adding them to the main view with a random center position. From there, I add UIDynamicBehaviors, as follows:

1) UIDynamicItemBehavior to stop the labels from rotating 2) UISnapBehavior to snap the labels to the center of the view (I want a gravity-like movement, but again, that's not this question) 3) UICollisionBehavior for all labels where the collisionMode is .Items.

This works in the "initial" setup...all the labels appear at random spots and then quickly snap together in the center, with proper collision detection. My question is, though, how can I then move a label (through a pan gesture) such that collision detection continues?

I have setup a UIPanGestureRecognizer on each of the labels, and when they start dragging I create a UIAttachmentBehavior and use that to move them as I drag. This "works" in the sense that the label moves, but it'll just glide over all the other labels without any collision detection happening. How can I achieve this collision detection, so that when I start dragging one label towards others, they move out of the way just enough for there to be no overlap (and then those snap back to their positions based on the center-gravity point)? Do I need to attach a UIAttachmentBehavior to all the other labels to the one I'm dragging for each pan?

I've created a test project for the issue I'm facing, which shows off what I just described:

github test project

Thanks!


Solution

  • Well, after several months of pondering this issue, I finally thought of a solution so I thought I'd post it here for everyone's benefit later on.

    This is super easy to accomplish with a simple SpriteKit scene. I just create a small SKScene, add SKLabelNodes into that scene with whatever text/color/sizing I desire, and then add a SKFieldNode with radialGravityField. From there, physics properties are playable with through the physicsBody property of each node, and I can accomplish exactly what was desired by plugging into touchesBegan method of the scene and appropriately moving the appropriate node, with the physics engine taking care of collisions and bouncing for me.