How To Integrate Cocos2D and UIKit

Cocos2D is a great framework, but sometimes it’s handy to implement some of your game with UIKit. For example, it’s often useful to design your main menu, settings pages, and the like with UIKit and just use Cocos2D for your main game logic. You also might find it handy to use UIKit controls on top […] By Ray Wenderlich.

Leave a rating/review
Save for later
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Gratuitous Progress HUDs

If you’ve been running this on your actual device, you might notice that there are certain parts with an annoying delay – setting up Cocos2D for the first time, and compressing image to JPG format for email sending.

When you have long-running operations that the user hast to wait for like this, it’s nice to display an indiator that something is going on to make the app feel more responsive.

One simple way to do this is through a utility class I like called MBProgressHUD. Go ahead and download it, then drag MBProgressHUD.h and MBProgressHUD.m from the unzipped folder into your project. Make sure “Copy items into destination group’s folder (if needed)” is selected, and click Finish.

Then go to MainViewController.m and make the following changes:

// Add to top of file
#import "MBProgressHUD.h"

// Replace viewTapped with the following
- (IBAction)viewTapped:(id)sender {    
    if (_rootViewController == nil) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"Loading...";
        [self performSelector:@selector(viewWallpapers:) withObject:nil afterDelay:0.1];
    } else {
        [self viewWallpapers:nil];

// Add to the beginning of viewWillAppear
[MBProgressHUD hideHUDForView:self.view animated:NO];

This just displays a HUD as the viewWallpapers method we wrote earlier (which starts up the RootViewController) gets called. We schedule the viewWallpapers method to run after a slight delay so that the HUD has time to appear before we start running the code to initialize the RootViewController.

Next move to RootViewController.m and make the following changes:

// Add to top of file
#import "MBProgressHUD.h"

// Replace mailTapped method with the following
- (IBAction)mailTapped:(id)sender {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"Preparing wallpaper...";
    CCScene * scene = [[CCDirector sharedDirector] runningScene];
    HelloWorldLayer *layer = [scene.children objectAtIndex:0];
    UIImage *curImage = layer.curImage;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {        
        NSData *data = UIImageJPEGRepresentation(curImage, 0.8); 
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self mailData:data];

This runs the call to UIImageJPEGRepresentation on a background thread, with the HUD animating as this occurs.

Compile and run, and the app should be more responsive!

Displaying a progress HUD for a long-running operation

Gratuitous About Screen

The app is almost complete, except we need an About page! Feel free to skip this if you’re already pretty familiar with how to add new view controllers, but if you need more practice follow along!

Control-click on the MaskedCal group, and select New File. Choose iOS\Cocoa Touch\UIViewController subclass, and click Next. Enter UIViewController for Subclass of, make sure With XIB for user interface is checked, click Next, name the class AboutViewController.m, and click Save.

Click on AboutViewController.xib and make the following changes:

  • Select the View, and in the Attributes Inspector set the Orientation to Landscape.
  • Drag a UIImageView to fill the View and set the image to About_page_bg.jpg
  • Drag a UILabel into the View, set X=49, Y=132, Width=382, Height=104, Text Color to White, and Font to Heiti SC Light 16.0, Txt Alignment to Center, # of Lines to 0 (means unlimited).
  • Change the text to: “Vicki works with her husband to create iPhone and iPad apps. Find more of her wallpapers on her website,, as well as free art for app developers and tutorials for artists.”

At this point your screen should look like this:

The Interface Builder layout for the About View Controller

Then switch to AboutViewController.m and replace the shouldAutorotateToInterfaceOrienation with the following plus a new method:

- (void) viewWillAppear:(BOOL)animated
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [super viewWillAppear:animated];

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    return UIInterfaceOrientationIsLandscape(interfaceOrientation);

Nice, now we just need to set up our main menu to display this. Open up MainMenuViewController.h and make the following changes:

// Add to top of file
#import "AboutViewController.h"

// Add inside @interface
AboutViewController *_aboutViewController;

// Add after @interface
@property (retain) AboutViewController *aboutViewController;

Then select MainMenuViewController.xib and control-drag from the About utton into the assistant editor’s MainMenuViewController.h. Set the Connection type to action, the name to aboutTapped, and click Connect.

Then switch to MainMenuViewController.m and make the following changes:

// Add after @implementation
@synthesize aboutViewController = _aboutViewController;

// Add inside dealloc
[_aboutViewController release];
_aboutViewController = nil;

// Add inside aboutTapped
if (_aboutViewController == nil) {
    self.aboutViewController = [[[AboutViewController alloc] initWithNibName:nil bundle:nil] autorelease];
[self.navigationController pushViewController:_aboutViewController animated:YES];

Almost done – one more minor tweak for style. Open up MainWindow.xib and select the Navitation Controller\Navigation Bar. Select the Tint color, and set R=168, G=215, B=224 for a nice teal color to match the rest of the app:

Setting the tint color of a UINavigationBar

Also select the Navigation Controller \ Main Menu View Controller\Navigation Item and set the Title to Home.

That’s it! Compile and run, and now the app is complete – with an About page and all!

An about page for our app!

Where To Go From Here?

Here is the complete example project with all of the code from the above tutorial series.

At this point, you should be familiar with the basics of how to integrate Cocos2D with UIKit. If you have any questions, comments, or suggestions, please join the forum discussion below!


Over 300 content creators. Join our team.