Giving CocosSharp v1.7.0.0-pre1 a Spin

iOS screenshot of a hybrid screen showing a Xamarin.Forms ListView and a CocosSharp game splitting the screen.

If you didn’t see the announcement recently, the awesome people working on CocosSharp put out a new preview of CocosSharp v1.7 (v1.7.0.0-pre1). With it, comes a very cool new way of working with your game content, the ability to mix it with normal native Xamarin.iOS, Xamarin.Android, or Xamarin.Forms content. I wanted to poke at the last of those, because I’ve been buried in Xamarin.Forms code non-stop for quite a few months now.


Getting the CocosSharp project templates working the the v1.7.0.0-pre1 packages takes a few extra steps: restoring the pre-release CocosSharp.Forms NuGet package on your shared and platform projects. Once you get things in place, though, you can do some amazing things by combining Xamarin.Forms content with your CocosSharp game content.

If you want to just jump right into playing with the final code, the resulting solution is available in a GitHub repo. (I may continue to work on this repo, so if it ever looks too different, here is the exact commit to clone to get you to the end of this post.)

CocosSharp Project Templates Add-in

While we can spin up a new Xamarin.Forms project and add the CocosSharp bits, this also gives us a chance to play with a nice Xamarin Studio add-in. Open up the Add-in Manager from the Xamarin Studio menu and search for “cocos” (technically “CocosSharp project templates”) and give the Install… button a click. Let’s restart Xamarin Studio to let it pick up the new templates.

Adding the CocosSharp project templates add-in.

When Xamarin Studio comes back up, create a New Solution. In the New Project window, under Cross-platform > App, you should now see two new CocosSharp entries: CocosSharp.Forms Game and CocosSharp.Forms.Game Showcase. The former is just an empty project pre-wired to try to get plumbed up for CocosSharp (more on that later), and the later is a similar project but with a little sample game content. We will pick the Showcase one so we have something on the screen immediately. Select that template and hit Next. Give your sample app some basic information like App Name. (I left everything else with the defaults, like PCL for shared code and Git integration, but feel free to customize.)

Package Restore Failure

Once you let Xamarin Studio spin up all the parts of your new solution, you’ll be presented with one of the hiccups with playing around with pre-release libraries.

Error restoring pre-release NuGet packages on the CocosSharp project templates.

By default, the NuGet package restore on our new project will fail because the CocosSharp packages it references are still in pre-release mode. If you open up the Package Console pad, you’ll see a message like this. (Note: when v1.7.0.0-pre1 is updated to go live, this won’t be an issue anymore.)

Adding CocosSharp.Forms… Attempting to resolve dependency ‘Xamarin.Forms’. Attempting to resolve dependency ‘CocosSharp’. Unable to resolve dependency ‘CocosSharp’.

If you don’t even notice this error and try to compile the project anyway, you’ll get various build errors as it tries and fails to resolve various CocosSharp namespaces.

CocosLovesXamarinForms.cs(7,7): Error CS0246: The type or namespace name `CocosSharp’ could not be found. Are you missing an assembly reference? (CS0246) (CocosLovesXamarinForms)

We’ll have to add the NuGet packages ourselves. It’s not that the project templates are broken, really, they just need some help to work with the system as it is.

Adding Pre-Release Packages

Double-click on the Packages folder of your shared PCL project to open the Add Package dialog. Since we know we want a pre-release package, check the bottom-left box to “Show pre-release packages.” Then, search for “CocosSharp.Forms” and add the CocosSharp for Xamarin.Forms package to that project.

Adding the pre-release CocosSharp NuGet  package.

Now, your PCL project will build, but you will still see errors on your platform projects because they are missing the Xamarin.Forms packages. This is slightly confusing because we don’t need pre-release Xamarin.Forms packages. So, why wouldn’t those be restored? Well, they weren’t added to these projects directly. They were supposed to be added by way of the dependencies on the CocosSharp.Forms package. Since that didn’t restore, we didn’t get its dependencies either, apparently.

If You Only See White

As a warning, if you run off and just add Xamarin.Forms to the platform project(s), you will end up with projects that build and run “without errors.” Unfortunately, you won’t have anything but white on the screen either.

Running the CocosSharp template project without restoring the platform CocosSharp.Forms packages.

Because the CocosSharp.Forms package contains the custom platform renderers for the CocosSharpView used in the PCL code, without them you don’t see anything on iOS or Android.

CocosSharp.Forms All the Things

To get your game rendering on the platform projects, we also need to add the CocosSharp.Forms NuGet package to the iOS and Android platform projects the same way we did for the shared PCL project. (Make sure you check the “Show pre-release packages” checkbox each time to find it.)

With those packages in place, you can see your project template game in all its glory.

Android screenshot of the CocosSharp project template game.

iOS screenshot of the CocosSharp project template game.

Mixing UI and Game Worlds

Now that your CocosSharp game isn’t bound to the world of running only in full-screen, you can do some fun and crazy things. For example, if you want to mix a game with a Xamarin.Forms ListView, we can now do that.* (* Some restrictions apply.)

Let’s open up GamePage.cs and start making some adjustments (Cmd+., “GamePage.cs”, Enter). Currently, the constructor is just putting the game in place.

CocosSharpView gameView;

public GamePage ()
    gameView = new CocosSharpView () {
        HorizontalOptions = LayoutOptions.FillAndExpand,
        VerticalOptions = LayoutOptions.FillAndExpand,
        // Set the game world dimensions
        DesignResolution = new Size (1024, 768),
        // Set the method to call once the view has been initialised
        ViewCreated = LoadGame

    Content = gameView;

Because of the way things work with CocosSharpView, it has to know ahead of time what size to be; you won’t be able to just request something like LayoutOptions.FillAndExpand. When I need to pre-determine dimensions and still handle multiple layouts, I tend to grab for an AbsoluteLayout and then do the necessary layout in the LayoutChildren overrride.

CocosSharpView gameView;
ListView listView;
AbsoluteLayout mainAbsoluteLayout;

public GamePage ()
    listView = new ListView () {
        ItemsSource = "These are some words I want to display in a list".Split (new[] { ' ' }),
    gameView = new CocosSharpView () {
        // Set the game world dimensions
        DesignResolution = new Size (1024, 768),
        // Set the method to call once the view has been initialised
        ViewCreated = LoadGame
    mainAbsoluteLayout = new AbsoluteLayout () {
        Children = {

    Content = mainAbsoluteLayout;

protected override void LayoutChildren (double x, double y, double width, double height)
    base.LayoutChildren(x, y, width, height);

    AbsoluteLayout.SetLayoutBounds (listView, new Rectangle (0, 0, width, height / 2));
    AbsoluteLayout.SetLayoutBounds (gameView, new Rectangle (0, height / 2, width, height / 2));

With that in place, we get this wonderfully useless “game.”

iOS screenshot of a hybrid screen showing a Xamarin.Forms ListView and a CocosSharp game splitting the screen.

Android screenshot of a hybrid screen showing a Xamarin.Forms ListView and a CocosSharp game splitting the screen.

Xamarin.Forms: Switching TabbedPage Tabs Programmatically

iOS Switch Tabs and Push Page via button click

Sometimes, your app uses tabs to separate different user activities. Sometimes, though, those activities aren’t completely independent. When that happens, you need an action in one tab to cause the user to switch to another tab. I’ll show you how to do that in code using Xamarin.Forms. In case you haven’t already started your tabs, we’ll start from the beginning. (Note: while the UI parts can be done quite well in XAML, this post will do it all in code.)

First, Some Tabs

Just in case you haven’t already made your Xamarin.Forms tab system, we’ll start there. This is as simple as using an instance of TabbedPage. Since we will want a little more control over things going forward, let’s create a subclass inheriting from it.

public class MainTabbedPage : TabbedPage {
    public MainTabbedPage() {
        Children.Add(new somePage());
        Children.Add(new someOtherPage());

You simply make this the MainPage in your App, now, and you get tabs.

public class App : Application {
    public App() {
        MainPage = new MainTabbedPage();

If you run your app at this point, though, you’ll notice something fairly obvious missing from your tabs.

Android TabbedPage without a name

No titles, no icons. In fact, on iOS, you can’t even tell where one tab ends and another begins.

iOS TabbedPage without a name or icon

Tabs UI Details

Xamarin.Forms will convert the Title and Icon properties of its child pages into these tab properties. Let’s add those.

public class MainTabbedPage : TabbedPage {
    public MainTabbedPage() {
        Children.Add(new somePage() { Title = "Tab 1", Icon = "SomeIcon1.png" });
        Children.Add(new someOtherPage() { Title = "Tab 2", Icon = "SomeIcon2.png" });

Android Tabs UI

iOS Tabs UI

The Icon property is of type FileImageSource. You can create one using the handy implicit conversion from a string as we did in the example above or create one manually.

somePage.Icon = ImageSource.FromFile("SomeIcon1.png");

A FileImageSource will use a platform’s native high-resolution image system (e.g., @2x/@3x for iOS, hdpi/xhdpi/xxhdpi for Android). For more information about using image resources in Xamarin.Forms, check out the handy image guide on the Xamarin Developer Portal.

Switching Tabs By Index

Your users can always switch tabs by tapping them. To switch the selected tab programmatically, you simply change the CurrentPage property of your TabbedPage.

CurrentPage = Children[1];

Without a reference to your child pages, you would be stuck using the index based on the order they were added. We could certainly do that if we want to hard-code what each index translates to. For instance, we could set it up to confuse our user by randomly switching tabs from the constructor. (Don’t do this.)

// NOTE: please don't randomly switch tabs on your user for fun.
Task.Run(async () => {
    var nextChildIndex = 0;
    while (true) {
        nextChildIndex = nextChildIndex == 0 ? 1 : 0;
        await Task.Delay(3000);
        Device.BeginInvokeOnMainThread(() => {
            CurrentPage = Children[nextChildIndex];

Not that this deserves analysis, but this is not terribly complex (which is ideal for a mock example). We start up an asynchronous Task that constantly waits three seconds before switching to the next tab (index 0 or index 1). We also make sure to swap the current page on the UI thread. Even though it looks like an loop that would lock up the app, the async/await means it is never waiting on the UI thread.

Switching Tabs By Reference

To be able to switch tabs by reference, let’s maintain the child pages in fields. Now, with a few switch functions, we can end up on the desired tab without worrying about indexes. At some point later, if you want to change the order of the tabs, you only need to change the order they are added to Children.

public class MainTabbedPage : TabbedPage {
    readonly Page tab1Page;
    readonly Page tab2Page;

    public MainTabbedPage() {
        tab1Page = new Page1() { Title = "Tab 1 title", Icon="circle.png" };
        tab2Page =new Page2() { Title = "Tab 2 title", Icon="square.png" };

        // To change tab order, just shuffle these Add calls around.

    public void SwitchToTab1() {
        CurrentPage = tab1Page;
    public void SwitchToTab2() {
        CurrentPage = tab2Page;

From within a tabbed page, you can now call to these methods by way of the Parent property.

public class Page1 : ContentPage {
    public Page1() {
        var button = new Button() {
            Text = "Switch to Tab 2",
        button.Clicked += async (sender, e) => {
            var tabbedPage = this.Parent as TabbedPage;
        Content = new StackLayout { 
            Children = {

In this case, we know that Page1 will only exist within a TabbedPage, but you could also exclude that code, or guard the switch call, with a conditional check to make sure you Parent is TabbedPage.

Switch and Push?

Now that you have a reference to each tab’s Page, you can also do a little work on the way there during a switch. For example, if your destination tab child is a NavigationPage, you could push a new page on its stack. In our prior example, we could accept a destination Page as a parameter on SwitchToTab1.

readonly NavigationPage tab1Page;
// ...
public async Task SwitchToTab1(Page pageToPush) {
    CurrentPage = tab1Page;
    if (pageToPush != null) {
        await tab1Page.PushAsync(pageToPush);

It may not have been obvious, but the signature of our switch function has changed from above. Since the PushAsync method is asynchronous, we should await it so any calling code can await this call as well. (Note: async void is potentially dangerous, so we give it a Task return type. For more background on this, check out this video by async-master Lucian Wischik’s

iOS Switch Tabs and Push Page via button click

Bonus Quirk: Android With Tabs + Navigation

If you have used Xamarin Forms enough, you know that things are rarely one-to-one between platforms. In this case, if you make a NavigationPage a child of a TabbedPage, it will look a little counter-intuitive on Android. The navigation is done first as the ActionBar and the ActionBar tabs sit directly underneath that bar, almost the opposite of the structure you created. This seems to be the expected representation of tabs in Android, so there may not be a workaround; and if there is, it may confuse Android users expecting the typical layout.

Sample Code

To see what would barely be called “finished code”, check out my Xamarin Forms TabbedPage GitHub repo of what I was working on while writing this article.

Abusing UIKit for Gaming in Xamarin.iOS, Part 3: Playing Sounds

This is the third in a [glacially-paced] series of Abusing UIKit blog posts giving some background on the development that want into producing Smudges, a simple game written entirely in Xamarin.iOS where fun shapes in various colors show up on the screen wherever a tap is detected. It was original created to give my two-year-old something fun to play while going tap-crazy on the screen. The game evolved from those “play-testing” sessions. If you have your own little ones and want something fun to distract them, Smudges is availabe on the App Store. At this point, I plan to continue adding features to it as I can. Let me know what you think about Smudges, or these blog posts, in the comments below or find @patridgedev on Twitter.

It's hard to show sound with a picture. This is where the sounds go when you play them. :P

Let There Be Noise!

Playing sounds in your apps can make for some great user interactions. Of course, it can also be used for far more annoying uses. For Smudges, each time an icon is placed on the screen with a tap, a random sound is played from a set of noises originally generated via as3sfxr (think Atari-era synth sounds).

As a disclaimer, this will only cover playing the random sound here and there. If you want timed, scheduled, or synchronized sounds, you will want to spend some time getting to know Audio Queue Services.

Getting Sounds Ready

Apple suggests different audio formats to meet different needs. Your project needs may vary, but if you aren’t doing crazy high-quality music tracks, there is a lot of flexibility.

You can play WAV, MP3, and CAF files. I wasn’t able to play OGG files directly, but there are lots of tools to convert between the various formats. I tend to use VLC to convert between various formats. At the risk of turning this into a tutorial about converting audio files, open VLC and go to File > “Convert / Stream…”.

  1. Select the source file
  2. Choose a profile to determine your output format
  3. Select “Save as File” and choose an output location

VLC audio format conversion example settings.

Sound, Meet Project. Project, Meet Sound

Whatever sounds and audio format you decide to use, add your sounds to the Resources folder in your iOS project. Feel free to use a subfolder to organize things however you prefer. Ultimately, you will end up with a file added to your project with a build action of “BundleResource”, ensuring it is set up for use at runtime.

Sound files added as project resources.

With your sounds in place, it’s just a few lines of code until you can start sending vibrations to your users’ ears.

Playing the Sounds

For these simple UI-style sounds, I find it best to throw an AVAudioPlayer at the problem. You spin one up with an NSUrl pointing to the resource, and tell it to play when you need it.

using AVFoundation;
var fileUrl = new NSUrl(NSBundle.MainBundle.PathForResource("Sounds/wubwub", "caf"), false);
var player = AVAudioPlayer.FromUrl(fileUrl);

If you want to help ensure your sound plays back immediately when asked to do so, you can tell the player to get itself ready to go.


For example, you can build up your audio player and immediately call this method in your ViewDidLoad method. Then, when your sound plays later, say, in response to an event handler firing, it is theoretically ready to go. The Apple AVAudioPlayer docs on this method don’t go into detail too much, but presumably this consumes memory and audio hardware resources. You will want to weigh the trade-offs in your playback based on the size/format of your sounds and how frequently you need each one.

When You’re Done…

If you want to run some code after your sound plays, AVAudioPlayer.FinishedPlaying is the event you’ll need.

player.FinishedPlaying += doSomethingCoolAfterSoundPlays;

In the sample code, I just throw a rotation animation at the button that triggered the sound. In the sample code, I just inline an event handler that rotates the button that triggered the sound. If you have a bunch of audio players, though, you could easily tie them all together to a common handler to save on lines of code.

Best Practices?

I’m not one to shy away from acknowledging when I don’t know something, and this is one of those times. When it comes to the best practices for audio playback, I only know what has worked well for me so far. A lot of the detailed information you find about playing audio on iOS is in game engines rather than hitting the core APIs directly. There is probably some value in digging into how these engines do their dirty work, under the hood.

Until then, I’ve gotten by pretty well with simple audio playback using the above technique. Smudges allows for simultaneous taps from 10 fingers (on iPads, iPhones only allow 5). When a pair of kids goes tap-crazy on Smudges all they can, it seems to hold up quite well, if not a little muddled. I have all my players in a list, and just grab a random one to play; that’s how the sample code does it as well. Take that for what it’s worth. If you find a better/safer way to do things, please do share in a comment below.

One last shameless plug…

Find Smudges on the App Store, available for iPhone, iPad, or iPod Touch. It’s especially fun on iPad where the hardware allows for ten simultaneous touch points.