Xamarin.iOS C# Recipe: Animating Views with iOS 7 UIGravityBehavior (UIKit Dynamics)

Now that iOS 7 has landed, and Xamarin gave us same-day C# support, it’s time to start poking at the new bits. One such piece is UIKit Dynamics. With UIKit Dynamics, you can greatly simplify all sorts of view animations. While this simple recipe will only address UIGravityBehavior, iOS 7 adds a bunch of other predefined behaviors and allows the creation of custom ones as well. Source code is available on GitHub. Basic Gravity Animation To have a view simply start falling off the screen, you just toss the desired view at a new UIGravityBehavior and add that behavior to a UIDynamicAnimator. UIDynamicAnimator animator; public override void ViewDidLoad() { base.ViewDidLoad(); View.BackgroundColor = UIColor.White; animator = new UIDynamicAnimator(View); var item = new UIView(new RectangleF(new PointF(50f, 0f), new SizeF(50f, 50f))) { BackgroundColor = UIColor.Blue, }; View.Add(item); UIGravityBehavior gravity = new UIGravityBehavior(item); animator.AddBehavior(gravity); } You can continue to put items under the effect of gravity by adding them to the behavior. gravity.AddItem(someOtherView); That’s really it for basic gravity, but craziness is only a step beyond that. You can modify the Angle, GravityDirection, and Magnitude of your gravity as well. Potential Memory/Performance Trap It’s worth noting that those items that go flying off the… Continue reading