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

UIGravityBehavior, oddly addictive

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);
}

Basic UIGravityBehavior

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 screen under the effects of gravity will continue to keep falling, even though they are no longer rendered on the screen. If you need to worry about resources, you could be computing locations for things long since forgotten.

Customizing Gravity

The three UIGravityBehavior properties, Angle, GravityDirection, and Magnitude, can all be changed to your liking and they are interconnected, changing one can affect the others.

Magnitude

The default gravity acceleration is 1000 pixels/sec^2. You could very easily bump the gravity to Jupiter levels (roughly 2.5 times that of Earth).

UIGravityBehavior gravity = new UIGravityBehavior(item) {
    Magnitude = 25000,
};

Direction (GravityDirection and Angle)

You can change the direction of gravity with two different interconnected variables, Angle and GravityDirection; change one and you affect the other. The default gravity angle pulls straight down, as measured in radians from the righthand side: PI / 2 radians, approximately 1.57. This is also expressed by the gravity direction vector, the default being (0, 1). Gravity’s direction can be adjusted to your whim, and reversing it is quite simple using a vector pointing the opposite direction.

UIGravityBehavior gravity = new UIGravityBehavior(item) {
    GravityDirection = new CGVector(0, -1),
};

Alternatively, with more math involved, you can set the radian angle.

UIGravityBehavior gravity = new UIGravityBehavior(item) {
    Angle = -(float)Math.PI / 2,
};

Action (Interacting with the Animation)

While not strictly a property for modifying gravity, UIGravityBehavior, like all the other behaviors in UIKit Dynamics, allows you to execute some code for each animation frame using its Action. You could use it for debugging a wonky behavior or for cleaning up views that you may have let fly off the screen.

UIGravityBehavior gravity = new UIGravityBehavior(item) {
    Action = () => {
        Console.WriteLine(item.Frame.Location);
    }
};

Bending Gravity to your Will (Advanced Recipe)

Having control over gravity can quickly go to your head. In the off chance you need to change gravity’s effect on your UI elements on demand, check out the secondary controller in the demo code. In this proof-of-concept, you tap to place an object under gravity’s control, simple enough with a UITapGestureRecognizer.

View.AddGestureRecognizer(new UITapGestureRecognizer((gesture) => {
    PointF tapLocation = gesture.LocationInView(View);
    var item = new UIView(new RectangleF(PointF.Empty, sizeInitial)) {
        BackgroundColor = ColorHelpers.GetRandomColor(),
        Center = tapLocation,
    };
    items.Enqueue(item);
    View.Add(item);
    gravity.AddItem(item);

    // ...
}));

Any time you want, though, you can swipe to alter its direction using a series of UISwipeGestureRecognizers (each one can only recognize a single swipe direction).

View.AddGestureRecognizer(new UISwipeGestureRecognizer((gesture) => {
    gravity.GravityDirection = new CGVector(1, 0);
}) { Direction = UISwipeGestureRecognizerDirection.Right, });
View.AddGestureRecognizer(new UISwipeGestureRecognizer((gesture) => {
    gravity.GravityDirection = new CGVector(-1, 0);
}) { Direction = UISwipeGestureRecognizerDirection.Left, });
View.AddGestureRecognizer(new UISwipeGestureRecognizer((gesture) => {
    gravity.GravityDirection = new CGVector(0, -1);
}) { Direction = UISwipeGestureRecognizerDirection.Up, });
View.AddGestureRecognizer(new UISwipeGestureRecognizer((gesture) => {
    gravity.GravityDirection = new CGVector(0, 1);
}) { Direction = UISwipeGestureRecognizerDirection.Down, });

I’m not sure I would call it a “game”, but I will admit to spending far more time poking at the screen than was necessary.

Controlling UIGravityBehavior by swipe

Keep Learning

Xamarin has put together a fantastic C# iOS 7 introduction and a great overview on iOS 7 UI changes. Expect more great iOS 7 C# tutorials to come out of Xamarin’s docs team as well as others participating in the Xamarin Recipe Cook-off. (Disclaimer: I am probably getting a free Xamarin t-shirt for this post.)

UIKit Dynamics are far more than just this one pre-baked gravity behavior. I highly recommend checking out the 2013 WWDC videos: Getting Started with UIKit Dynamics and Advanced Techniques with UIKit Dynamics.

MonoTouch Programming in Visual Studio

TL;DR

Never underestimate the little time sinks of switching between IDEs regularly. To write MonoTouch code in Visual Studio 2010 (debug/deploy still requires MonoDevelop on a Mac), go get VSMonoTouch. If you have any issues getting it going, you may need to toss in some project file tweaks.

Background

I’ve been programming with MonoTouch for a few months now using MonoDevelop. I really enjoy learning new things (even if MonoTouch saved me from learning Objective-C), but switching IDEs always tosses a few kinks in my productivity. I have tweaked a number of key bindings in MonoDevelop to match Visual Studio, some at the cost of my ability to adapt to the Mac’s defaults that are normally used everywhere. At one point I switched copy and paste to use Ctrl in MonoDevelop, but then I kept screwing up outside of the IDE. Regardless, I have become fairly productive in MonoDevelop from simply adapting to the new system through repetition (often screwing up when I switch back to Windows now).

I don’t really have a problem with MonoDevelop most days, but I definitely prefer the Windows system of maneuvering windows and working on multiple displays. Even if I were a Mac-only person, I would hate how full-screen mode works on a Mac. While I have adapted to my new MonoDevelop workflow, I definitely miss having multiple tabs open in a single project; to open multiple instances of MonoDevelop on a Mac, you even need a simple hack. Having to flip around between MonoDevelop and Chrome as I drink from the MonoTouch learning firehose only compounds the window management issue.

Nothing seems to get you around the need for a Mac when testing/debugging/deploying a MonoTouch project, but having Visual Studio as your primary IDE for all your .NET projects can definitely speed things up.

VSMonoTouch

Enter VSMonoTouch by Jonas Follesø (follesoe on GitHub).

This Visual Studio VSIX add-in (warning: requires a non-free Visual Studio) seems to create a system for allowing Visual Studio to recognize the MonoTouch framework and its project type and use the correct DLLs for compiling. For simplicity’s sake, just follow the instructions in the project README for your first run. If that doesn’t work, start looking for tweaks.

The final process I used was simply moved the VSIX install step from first to last on the instructions list from the README (with absolutely no reason to explain why it worked). Regardless, feel free to try some restarts on the off chance you have issues.

  1. Copy the MonoTouch binaries from your Mac development environment to your Visual Studio 2010 development environment. Copy all the files from /Developer/MonoTouch/usr/lib/mono/2.1/ on your Mac to C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v1.0 on your PC.
  2. Add a RedistList-folder under your newly created v1.0-folder. Download the FrameworkList.xml file and add it to the RedistList-folder.
  3. Download and run the vsix-package from the github page.

Code Reference Quirks

It seems that some systems have an easier time getting VSMonoTouch to run than others. On my Windows 7 machine with Visual Studio 2010 (10.0.40219.1 SP1Rel), .NET 4.5, and various Visual Studio 2012 free components; I had a few issues getting things just right. The first three times I tried things out, I simply couldn’t get Visual Studio to acknowledge the project type. It would load the solution I have from MonoDevelop but leave the projects unloaded.

I tried all sorts of variations on the FrameworkList.xml file and gave up for a while.

mscorlib

Today, I decided to try again after I noticed a few updates to a project issue with mscorlib. That wasn’t the issue I was having, but I was hoping anyone trying to solve this issue may accidentally find a solution to help my problem. Oddly, after installing the DLLs first and then the VSIX, it all started loading correctly but with some compile errors and warnings.

  • Error: “An assembly with the same identity ‘mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′ has already been imported. Try removing one of the duplicate references.”
  • Warning: “No way to resolve conflict between “mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″ and “mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″. Choosing “mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″ arbitrarily.”
  • Warning: “There was a mismatch between the processor architecture of the project being built “MSIL” and the processor architecture of the reference “C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll”, “x86″. This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.”
  • Warning: “Found conflicts between different versions of the same dependent assembly.”

This is where that [mscorlib project issue] came into play. There was a note on the VSMonoTouch README about making sure to have explicit mscorlib references, but I already did. Checking the box on the “Do not reference mscorlib.dll” project property, though, removed those errors.

VSMonoTouch mscorlib.dll issue fix

If you are a fan of tweaking csproj XML directly instead of through the project properties editor, feel free to add this node to any compilation PropertyGroups manually.

<NoStdLib>true</NoStdLib>

System.Web.Services

After fixing the mscorlib.dll issues, though, I got a new error popping up. This final compile error was coming from code I wrote, so that was a good sign (I guess).

  • Error: “The name ‘HttpUtility’ does not exist in the current context”

Since I am writing an application that interfaces almost entirely with the web-based JSON API I wrote, there are a few places where I am sending back user content to that system. The URL encoding I use simply hits HttpUtility.UrlEncode. In MonoTouch, you need to make sure you reference System.Web.Services to get UrlEncode. But, in Visual Studio Land, the .NET 4.0+ DLL doesn’t have such a method. You can fix this issue with a static version reference on that DLL. There may be a version-agnostic way to do this, but I ended up editing my csproj file to point to the specific version found in the MonoTouch DLLs.

<Reference Include="System.Web.Services, Version=2.0.5.0" />

I will probably have to update this manually whenever a new version hits MonoTouch, but I definitely can live with that.

VSMonoTouch In Use

After getting the loading and compile errors worked out, I now have a MonoTouch solution building successfully in Visual Studio 2010. It contains a core project shared with the Sierra Trading Post Android app (using a few compiler directives) and my MonoTouch project containing almost entirely UI-related code. I write some code and it tells me whether it will compile correctly against the MonoTouch DLLs. I haven’t tried abusing the reliability of this system with any features that are not part of Mono (e.g., async/await) or MonoTouch (e.g., dynamic) yet.

Since my project is currently synced through Dropbox, I just save what I have on Windows and roll on over to the MacBook to run things on the simulator or deploy them to a physical device and/or TestFlight (which is far better than sliced bread, at least for getting your app out to multiple devices). MonoDevelop will even automatically update your project files if you already have it open, though I don’t recommend editing on both systems simultaneously without having something between them to handle conflicts that are bound to arise.

Creating an animated spinner in a Xamarin.iOS (MonoTouch) UIImageView

Background

I’m well into my first week of building the Sierra Trading Post first iOS app using Xamarin.iOS and it has been a fun ride so far. One of the first things needed was a system for showing a loading image while asynchronously retrieving the final image with a web request.

Attempt 1

Xamarin has a recipe for using a UIImageView‘s AnimationImages to make a spinner.

UIImageView someImageView = new UIImageView();
someImageView.AnimationImages = new UIImage[] {
    UIImage.FromBundle("Spinning Circle_1.png"),
    UIImage.FromBundle("Spinning Circle_2.png"),
    UIImage.FromBundle("Spinning Circle_3.png"),
    UIImage.FromBundle("Spinning Circle_4.png"),
};
someImageView.AnimationRepeatCount = 0; // Repeat forever.
someImageView.AnimationDuration = 1.0; // Every 1s.
someImageView.StartAnimating();

It may be possible to make this work, but it wasn’t quite what I needed. This seems to be more of an image rotation than an animation. As a result, it creates a jerky animation between the various images equally distributed over the AnimationDuration you set.

After this, attempts to find some ideas for a better solution lead me to about a hundred lines of code that proved a difficult to consume, involving a CGBitmapContext and CGAffineTransform.MakRotation. (To be fair, this code isn’t doing something as simple as what I want to do.) Hoping to avoid that, I simply added four more rotation positions into the list. It would probably take many more to make it appear smooth. Any more than that and I really didn’t want to bloat my project with minute rotations of the same PNG. Back to Google I went.

Solution

After enough poking around some slightly related Google results, I began to understand enough of CABasicAnimation to see how it could work for the job. You create the desired animation and add an instance of UIImageView.Layer.

    // Image to be rotated (in this case, found in the project as "/Assets/Images/loading_icon.png").
    UIImageView someImageView = new UIImageView(UIImage.FromBundle("Assets/Images/loading_icon"));
    CABasicAnimation rotationAnimation = CABasicAnimation.FromKeyPath("transform.rotation");
    rotationAnimation.To = NSNumber.FromDouble(Math.PI * 2); // full rotation (in radians)
    rotationAnimation.RepeatCount = int.MaxValue; // repeat forever
    rotationAnimation.Duration = 1;
    // Give the added animation a key for referencing it later (to remove, in this case).
    someImageView.Layer.AddAnimation(rotationAnimation, "rotationAnimation");

The main part of this is the simple rotation CABasicAnimation that is applied to a Layer of a UIImageView. In this case, it is set to do a full rotation (accepted in radians) every one second through a very large number of repetitions. The repetitions is actually one oddity in the switch to this new method. When you set UIImageView.AnimationRepeatCount, you can set it to zero to make it loop forever. Oddly, a CABasicAnimation.RepeatCount set to zero is the same as one, and it loops a single time before stopping.

Code (Example doing for a bunch of UITableView cells)

static NSString key = new NSString("somecellkey");
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) {
    UITableViewCell cell = tableView.DequeueReusableCell(key);
    if (cell == null) {
        cell = new UITableViewCell(UITableViewCellStyle.Default, key);
    }

    // Image to be rotated (in this case, found in the project as "/Assets/Images/loading_icon.png").
    cell.ImageView.Image = UIImage.FromBundle("Assets/Images/loading_icon");
    CABasicAnimation rotationAnimation = CABasicAnimation.FromKeyPath("transform.rotation");
    rotationAnimation.To = NSNumber.FromDouble(Math.PI * 2); // full rotation (in radians)
    rotationAnimation.RepeatCount = int.MaxValue; // repeat forever
    rotationAnimation.Duration = 1;
    // Give the added animation a key for referencing it later (to remove, in this case).
    cell.ImageView.Layer.AddAnimation(rotationAnimation, "rotationAnimation");

    // Do your lazy-loading of the image (blog post coming soon...maybe).
    ...

    // For a good time, you can keep rotating your final, lazy-loaded image by not calling this line.
    cell.ImageView.Layer.RemoveAnimation("rotationAnimation");

    // Do the rest of your visual stuff to the cell.
    ...

    return cell;
}

More Code

If you want a quick demo application of the differences, check out the GitHub repo I put together [and finally got around to sharing]. It is a simple demo of two UIImageViews that implement the two methods here. Clicking anywhere will toggle between the two.

Here’s a quick video snippet of the demo code running.