Social Icons

twitterfacebookgoogle pluslinkedinrss feedemail
Showing posts with label Cocos2d. Show all posts
Showing posts with label Cocos2d. Show all posts

Wednesday, October 31, 2012

Installing cocos2d Templates with Xcode 4

Cocos2d is a powerful framework that is used to power countless games for iOS – the purpose of this article is to get you up and running with the cocos2d templates and get them installed on Xcode 4.

Before we begin, you must have Xcode and Apple's developer tools actually installed – to install Xcode, simply head over to the Mac App Store and search for Xcode and then install and run the app and you'll be ready to go!

I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too. 

Stay tuned to my blogtwitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.

This article is related to

iPad,iPhone,iPhone Resources,iPhone Articles,iPhone Development,iPhone Turorial,Mobile Development Tutorials,Mobile Developments,Objective C,xCode,xCode 4,Cocos2D, Cocos2D Templates

Saturday, October 13, 2012

Tutorial: How To Quickly Create A Game Using The CocosBuilder Cocos2D Editing Tool

Today's iOS Developer resource is a tutorial from Zynga showing how to create a game using the free Cocos2D scene building tool CocosBuilder. This is an easy to follow tutorial but very in-depth covering not only how to lay out the game, but how to create animations with CocosBuilder.

You can find the source code on Github here.

You can find the full tutorial here.

You can find the Cocosbuilder tool here.

A nice easy to follow tutorial that will really help you get a grasp on using the CocosBuilder tool.

I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too. 

Stay tuned to my blogtwitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.

This article is related to

iPad,iPhone,iPhone Resources,iPhone Articles,iPhone Development,iPhone Game Development,iPhone Turorial,Mobile Development Tutorials,Mobile Developments,Objective C,CocosBuilder,Cocos2d,Game Engine

Saturday, April 9, 2011

iPhone Tutorials

iPhone Tutorials

This site contains a ton of fun tutorials – so many that they were becoming hard to find! So I put together this little page to help everyone quickly find the tutorial they’re looking for. Hope you enjoy! :]

Beginning iPhone Programming

iPhone programming is like a ladybug - fun and only a little scary!
iPhone programming is like a ladybug - fun and only a little scary!
If you’re completely new to iPhone programming, start here! First there’s a tutorial series that will walk you through the process of creating an iPhone app from start to finish – using the most common APIs that almost every app uses. Next there’s a tutorial about memory management – the area where beginners most often get confused about!

Game Programming with Cocos2D, Box2D, and Chipmunk

Ninjas Going Pew-Pew!
Ninjas Going Pew-Pew!
If you want to make games on the iPhone, the easiest way by far is to use the Cocos2D iPhone framework and the physics libraries that come with it – Box2D and Chipmunk. These tutorials will help get you started by showing you how to make some simple games and solve common problems.
In addition to these tutorials, you might be interested in the Cocos2D book Rod Strougo and I are working on.

Game Programming and Development

Tomato-San says: w00t, it's done!
Tomato-San says: w00t, it's done!
While we’re on the topic of game programming, here are a few posts with some tips and tricks for game developers.

Saving and Loading Data

Core Data Failed Banks Model Diagram
Core Data Failed Banks Model Diagram
Almost every app needs to save and load data on the iPhone – and there are many different ways to do so. In these tutorials, you can get hands-on experience with many of the most common methods.

Graphics and Animation

Welcome to Core Graphics 101!
Welcome to Core Graphics 101!
In order to be successful on the App Store these days, your app needs to look good. Here are a few tutorials that you can use to up the quality level of your apps, and your gain mad skills with graphics and animation programming.


Screenshot from BasicSounds sample project
Screenshot from BasicSounds sample project
When I first started iOS programming, I knew a WAV file played sounds and that was about it. These posts explain a lot about audio files and formats, and explain how you can play audio in your apps.

iPad Development

What it will look like when we're done!
What it will look like when we're done!
If you know how to program for the iPhone, it’s a simple matter to program for the iPad as well! These tutorials walk you through some of the differences and help get you started with some of the new APIs available on the iPad.

3rd Party Libraries

I have a soft spot for malteses!
I have a soft spot for malteses!
There are a lot of third party APIs and SDKs you might want to include in your apps. These tutorials cover a few of them and show you how to get started.

Training and Announcements

One day class introducing iOS programming for beginners!
One day class introducing iOS programming for beginners!
From time to time I announce upcoming training, books, and other types of announcements from this site. Here’s the news so far!


1) Integrate iAd 2) ??? 3) PROFIT!
1) Integrate iAd 2) ??? 3) PROFIT!
There’s always something that doesn’t fit anywhere else! Here’s a hodgepodge of other posts and tutorials you may find interesting.

Saturday, November 27, 2010

Cocoa With Love : The design of an iPhone application

In this post, I'll discuss iPhone program design using the example of a small but non-trivial iPhone application to provide examples of how the design is implemented. The design includes: how to manage data coming from different sources, how to manage multiple views of that data and how to design your program so it remains simple and manageable as it grows. In short, I'll be discussing how Model-View-Controller (MVC) applies to an iPhone application but I'll also discuss how even simple programs are considerably more hierarchic through their controllers and branched through their models and views than the basic description "Model-View-Controller" might imply.

The sample program

The sample program for this post takes the Core Data SQL database of Australian Postcodes that I created last week from a CSV file and uses that in an iPhone application that allows you to:
  • Browse and search the database.
  • Display entries in a MKMapView.
  • Find the nearest entry to the user's GPS and display that on a map.
The following screenshots show the basic flow of the application.
IMG_0018.PNG IMG_0020.PNG IMG_0021.PNG The "Show current location" step skips the middle screenshot in the workflow and goes straight to the map, displaying the closest "Postcode" in the database for the user's location, or just the user's location (with no pins in the map) if they are more than 0.1 longitude or latitude away from the nearest post office.
You can download the complete project (961kB).

Steps in designing a program

The basic steps in designing a small user program are:
  1. Decide what the program will display to the user.
  2. Work out how the user will navigate through the program to reach each view.
  3. Work out the data that is needed to populate the views that the user will navigate.
  4. Decide where that data will come from and how you will manage access to it.
  5. Decide how and when you will construct your views.
  6. Decide how you will provide your views with data.
The first two points are the program's requirements and the remainder is the high level design. For this post, I'm going to consider the first two points complete (as given in the previous section).
I'll discuss steps 3 and 4 as a single concept "Program data", then steps 5 and 6 as "Program construction".

Program data

While it might not be obvious, this program actually has 5 different sources of data:
  • Postcodes and their related data
  • The GPS location
  • The cache of fetched postcodes, filtered by search terms
  • The cache of postcodes nearest the selected location or GPS location
  • List of menu items on the top-level page
The last item doesn't need to be data (it could easily be done in code) but I wanted to talk about a range of different data sources and implementing menus like this from data can dramatically reduce the size and complexity of your code (see my earlier post Simplifying your code using NSDictionary).
Postcode data and the PostcodeController
Obviously in this program, the Core Data SQL database is the source of the postcode data. However, there is more to clarifying the data source than that.
The postcode data is used from multiple views in the application. For this reason, it will need to live in its own persistent location that views can access when needed. To handle its creation, persistence and access, we'll need some form of controller to manage the lifecycle of this data and access to it.
Core Data runs in an NSManagedObjectContext. In some respects, you may consider that the NSManagedObjectContext manages access to the data. While this is true at the low level of reading, writing, cacheing and fetching, the reality is that NSManagedObjectContext is not a manager in a broader sense for your program and your program specific logic.
Specifically, your program will need:
  • A way to construct the Core Data persistence stack (i.e. open a Core Data SQL store and create an NSManagedObjectContext for it).
  • A way to access the current context from anywhere in the program.
  • A place to put context processing code (if needed). This might include importing/exporting code, specialized fetching code, editing and validating code.
While this iPhone application doesn't need the last point, the first two are necessary.
In the default Xcode template for an iPhone application using Core Data, the NSManagedObjectContext is constructed in the AppDelegate object and from there is pushed onto the RootViewController so that it can be used there.
Simply put: I dislike this approach because it gives the AppDelegate multiple responsibilities unrelated to its primary purpose.
The AppDelegate exists to implement functionality during key points in the UIApplication's lifecycle (most importantly startup and shutdown). The AppDelegate doesn't use the NSManagedObjectContext for itself and the AppDelegate's primary responsibility is not document management — you should not be using your AppDelegate as your application's document manager.
Every class should have a single purpose
Every piece of functionality that a class exposes to the rest of the program (i.e. functionality that is part of the class' external interface) should be obviously part of that class' primary role in the program.
For this reason, I create a class (in this project it is named PostcodesController) whose responsibility it is to construct the document (our NSManagedObjectContext) and handle access to it or process the document if needed.
The PostcodesController will be a singleton, as most document managers are (see the NSDocumentController in Mac OS X). Since the application only has one set of Postcode data, there is no need to select the "current" document or manage a set of Core Data persistence stacks but this class is where that behavior would be added if needed in future.
The PostcodesController is then acccessed by the PostcodesViewController to get the current context. However, the data this context contains is not used directly; it is cached by the NSFetchedResultsController as a separate set of data and from there it is used to populate the table view.
Map data
Map data in the application consists of three parts:
  • The map "tiles" (the street map shown in the view)
  • The "current location" (which is either the result of a selection or the GPS location).
  • The array of pins displayed in the map
The actual map tiles are loaded by the MKMapView that Apple's MapKit provides. We don't really need to worry about that.
The selected location or GPS location is a little trickier. This either comes from the user's selection on a previous screen or from the CLLocationManager (which supplies us with location data from the GPS). If this was used by multiple views in the application, then we would need a special class to manage the current location for the whole application (like the PostcodeController manages the postcode database for the whole application) however, we only need location data on the map screen, so the MapViewController which manages this screen can handle this.
The array of pins displayed on the map is really just a selection of the data from the postcodes database, selected using criteria from the current location. Again, since this is only used on the map screen, so it can be controlled by the MapViewController as long as the difficulty of doing so remains low.
List of menu items
Sometimes, data is so simple to load and so customized to the location where it will be used that managing it is no concern at all. The array of dictionaries that provides the structure for the "Main Menu" in the program is a good example of this — the data can be read in a single instruction, its format is written to match the format that the "Main Menu" wants, it has no state to maintain and doesn't require any editing.

Program construction

This program started with a "Navigation-based application" template in Xcode and the project name "AustralianPostcodes". This means that the following steps are setup by the template:
  1. The UIApplication will load the MainWindow.xib on startup
  2. The MainWindow.xib will construct the AustralianPostcodesAppDelegate, a UIWindow and a UINavigationController which will load the RootViewController from RootViewController.xib and set it as the top level view in the navigation hierarchy.
  3. The AustralianPostcoddesAppDelegate will insert the UINavigationController's view into the UIWindow and display the window.
The primary controllers in the program are the PostcodesController (which controls the construction of the Core Data persistence stack), the RootViewController (which shows the main menu), the PostcodesViewController (which displays the table of objects fetched from Core Data) and the MapViewController (which displays a single Postcode object and the map view).
Constructing the RootViewController
The RootViewController needs to display its list of options in the table. When any row in the table is tapped, a new UIViewController subclass will need to be constructed and pushed onto the UINavigationController.
Due to the data-configured nature of the RootViewController, the subclass of UIViewController constructed and any parameters passed into its initializer are all specified in the data file.
This means that this class is incredibly simple. The three different rows perform three different tasks:
  1. Load a PostcodesViewController and sort by postcode
  2. Load a PostcodesViewController and sort by suburb
  3. Load a MapViewController and use the GPS for location data
But the differences come from the data. The work done by the RootViewController is the same in each case.
Constructing the PostcodesViewController
This class displays the postcode data but it has to perform four tasks as part of that job:
  1. Fetch the sorted (and possibly filtered) postcodes from the database
  2. Construct/configure the table view cells to display the fetched results in the table
  3. Respond to changes in the search string by refetching the data
  4. Respond to taps on a row by loading a MapViewController to display the map
In this case, much of the first step is handled by a standard NSFetchResultsController. This class is designed to work closely with the UITableView so it makes sense to keep this work close to the view. If we weren't using an approach so closely tied to the view, it would also be possible to put a fetch method in the PostcodesController and pass parameters to it so that it prepared the data in an appropriate format.
When a row is selected, the Postcode object (the subclass of NSManagedObject associated with the selected row) is passed into a newly constructed MapViewController.
Constructing the MapViewController
The MapViewController needs to perform the following tasks:
  1. If not given a selected Postcode object, then the Postcode in the database nearest the GPS location must be fetched.
  2. Postcodes around the current location must be fetched and displayed on the map
  3. The map view must be centered on the selected postcode
  4. Details about the selected postcode must be displayed in the UILabels at the top of the screen.
To enable the easy display of postcodes as points on the map, the Postcode class (the subclass of NSManagedObject used by the Postcode entity in the Core Data model) implements the MKAnnotation protocol. This means that the Postcode objects returned from a fetch can be immediately added to the MKMapView.
This class needs to perform its own fetching from the Core Data database. Since the PostcodesViewController and MapViewController both need to fetch (albeit in slightly different ways) and they both use a significant volume of code of to do this fetching, it is possible that a common interface to perform fetch actions for both would be a future improvement.
Always be ready to iteratively refactor
As you implement a program, you should always be on the lookout for easy ways to simplify your program by implementing minor redesigns. Looking for multiple places where your program repeats the same functionality is the most prominent example of this. A corollary to this is that you should never copy and paste blocks of code — a copy and pasted block of code should be a single method/function/macro that you simply invoke from multiple places.


Interpreting this program according to model-view-controller would go like this:
  • Model — the Postcode objects in the NSManagedObjectContext are the model.
  • View — the UITableViewCell objects on the "Main Menu", "By suburb" and "By postcode" screens and the MKMapView on the map screen.
  • Controller — the AustralianPostcodesAppDelegate, RootViewController, PostcodesViewController, MapViewController, PostcodesController.
Why do we need so many controllers?
An interesting point to note is that every class in the project (with the exception of Postcode) is a controller class.
Why do we need so many controllers? The answer is that we have a normal number of controllers — the correct analysis is that we have is an absence of custom model and view objects.
A well written model object or view object needs no custom code for customization — the construction provided by the controller and the data (provided from configuration files on construction or from model objects when loaded) is all the customization that they require.
I've written posts about drawing customizing table views without subclassing any views — the customization comes from how the view is constructed and set up.
On the model side, NSManagedObject is configured by the .xcdatamodel file and can be used without further configuration if desired. Similarly, NSDictionary is used by the RootViewController to hold custom structure data without need for custom behavior.
Obviously you will probably need custom model and view objects at some point but the fewer you have, the easier things will be.
A simple diagram of the program
basicMVC.png Generally though, I don't like this type of over-simplification. My problem is that while it does describe a single Model-View-Controller path through the program, this program has multiple sources of data and each source of data is managed at a different point and displayed in a different way.

A different way to think about application design

Despite the simplistic diagram shown above, the reality is that we have the following model-controller relationships in the program:
  • The Postcodes in the NSManagedObjectContext, controlled by PostcodesController
  • The Plist which describes the Main Menu, controlled by RootViewController
  • The cached fetch of Postcodes by suburb or postcodes, controlled by NSFetchedResultsController in conjunction with PostcodesViewController
  • The cached fetch of nearest Postcodes, controlled by MapViewController
  • The GPS location, controlled by CLLocationManager
So a full diagram of the data paths through the program would be considerably more complex than the diagram shown above.
An important point to note about the above diagram is that there are two layers of controllers: one layer that controls the model at the top and one layer that controls the views at the bottom. The result of this observation is that the view-and-controller pairs and the the model-and-controller pairs are really two instances of the same design pattern. This means that we can add the following view-controller relationships to the list of model-controller relationships shown above:
  • The UITableViewCells in the UITableViews, controlled by PostcodesViewController and RootViewController
  • The UILabels and the MKMapView, controlled by the MapViewController
What this does is to break the entire program down into pairings of:
  • Class that "does" something (store data, display data, fetch data)
  • and Controller which loads and configures it
Your program is then a hierarchy of controllers (UIApplication/AppDelegate, Document controller, UIViewController subclasses) which load and configure their own modules (.xib files and windows, Core Data, UIView classes) to perform their actual work — but these modules have no connections to the rest of the program, they rely entirely on the controller to set them up, provide their data and make them work.
As your program grows larger and more complex, your controllers may have sub-controllers — in fact, your module objects may become controllers to their own sub-module objects. Through this structure, you can have a giant program but each element is still simple within itself. Simplicity remains as the program grows because every individual element is self-contained.
Implications of this way of thinking
The best programs are highly modular and decoupled
A good application has tightly focussed modules which are totally decoupled from the rest of the program and controllers which are lightly coupled to other controllers in a hierarchical arrangement through the program but do nothing other than provide the contextual information for their controlled objects.
The idea is to make all aspects of your program clean, decoupled and resusable, in the same way that good view and model classes are.
I prefer this way of thinking about application design. In essence, treat every data object, every network connection and every view object in the program (any class which "does" something) in the same way: like its own independent module. These independent module classes should:
  • have their own controller which loads and configures them
  • not have a connection (pointer or reference) to any other part of the program (except other objects within the module)
If you feel like one of these module objects needs to access another part of the program, try to redesign so that the controller pushes the information to the modular class, instead of the module object fetching for itself.
The corollary to this is that your controller objects should, as much as possible, avoid "doing" anything except constructing and configuring these document-like objects. Controllers may have a lot of code compared to the module classes but that code should always be responding to a change from a module object and passing a message to another module or constructing another module. Controllers are all about setup, reactions and inter-module communication.
Most of the time, the module objects controlled by the controller will not be your own special subclasses — often they're just default NSDictionary objects or UIViews or NSManagedObjects — but it is important to keep the module object and controller relationship in mind to help guide how you write your program.
Keep the main advantage of Model-View-Controller thinking
Even if you do start thinking about every component in your program in module-controller terms, you shouldn't drop the key advantage of Model-View-Controller — to focus your application around the workflow of your "model".
Specifically: you should always know what the "model" of your program is. All aspects of your program should be directed towards showing, editing, displaying that data. Even if lots of other modules, tasks and activities are implemented as part of the overall process, they should not disrupt the model's workflow.


You can download the complete project (961kB).
I wrote a lot of code for this post but I've included none of it here. The code exists to make the abstract discussion about how to design a program seem less abstract — I hope that you can look at the code and understand the sometimes vague statements I've made in this post.
The first half of the post was about identifying the data your program has and then identifying how to build the controllers in your program to load and display this data. The purpose of going through these steps is to explain that these are the details you must have clear in your mind before you start writing code. Programming requires — above all else — that you be able to absolutely and unambiguously clarify your idea.
The second half of the post was about module-controller relationships. The purpose here is not to say Model-View-Controller is wrong but to point out that the purpose of Model-View-Controller is decoupled, reusable modules with all construction and context provided by hierarchy of lightly coupled controller objects running through the spine of your program — and that this is a pattern that can be applied repeatedly (and even recursively) throughout your program, not just to views or your main model.

Cocoa With Love : Showing a "Loading..." message over the iPhone keyboard

Showing a "Loading..." message over the iPhone keyboard

The "Text" (SMS) application on the iPhone uses a custom, semi-transparent view to show its "Sending..." message over the keyboard. I'll show you a simple class that can display semi-transparent loading messages and how you can display messages over the keyboard.


"Loading..." messages
When waiting for data loaded from the internet, many iPhone applications use a mostly black, semi-transparent view to block the display. Most use a basic "spinner" (UIActivityIndicatorView) to reassure the user that the application is still running, frequently accompanied by "Loading..." text.
Despite the prevalence of this type of loading message, it is not a standard control and must be constructed manually.
Finding the keyboard
Apple give no methods to locate the keyboard or even the current first responder in an iPhone application. I'll show you how you can find both.
The sample application
The sample LoadingView application in this post can display the following two types of loading window:
A full-window loading message and a keyboard-only loading message.
The sample application doesn't actually load anything. The "Refresh" button displays the full-window loading message for 5 seconds and the text field lets you enter some text and hit "Send" to see the keyboard-only loading message for 5 seconds.

Displaying a loading view

A loading view is not the most complicated piece of custom user-interface but there are a handful of common behaviors it should implement so it is a good idea to have a reusable class for the purpose.
The behaviors in my loading view include:
  • Always fill the whole view that it blocks (even though it looks inset on all sides for aesthetic reasons).
  • Fade in and fade out when added and removed.
  • Semi-transparent, allowing the unloaded view to show through.
  • Autoresizeable so that a portrait to landscape rotation during loading won't disrupt the display.
  • Displays a centered status message and activity indicator.
To ensure that these behaviors are applied to the view on construction, I use a loadingViewInView: method instead of a normal constructor. This method constructs, adds to superview and handles the fade animation all at once.
+ (id)loadingViewInView:(UIView *)aSuperview
LoadingView *loadingView =
[[[LoadingView alloc] initWithFrame:[aSuperview bounds]] autorelease];
if (!loadingView)
return nil;

loadingView.opaque = NO;
loadingView.autoresizingMask =
UIViewAutoresizingFlexibleWidth |
[aSuperview addSubview:loadingView];

// Code to create and configure the label and activity view goes here.
// Download the sample project to see it.

// Set up the fade-in animation
CATransition *animation = [CATransition animation];
[animation setType:kCATransitionFade];
[[aSuperview layer] addAnimation:animation forKey:@"layerAnimation"];

return loadingView;
All that's required to make it look semi-transparent is a custom drawing method.
- (void)drawRect:(CGRect)rect
rect.size.height -= 1;
rect.size.width -= 1;

const CGFloat RECT_PADDING = 8.0;
rect = CGRectInset(rect, RECT_PADDING, RECT_PADDING);

CGPathRef roundRectPath =
NewPathWithRoundRect(rect, ROUND_RECT_CORNER_RADIUS);

CGContextRef context = UIGraphicsGetCurrentContext();

const CGFloat BACKGROUND_OPACITY = 0.85;
CGContextSetRGBFillColor(context, 0, 0, 0, BACKGROUND_OPACITY);
CGContextAddPath(context, roundRectPath);

const CGFloat STROKE_OPACITY = 0.25;
CGContextSetRGBStrokeColor(context, 1, 1, 1, STROKE_OPACITY);
CGContextAddPath(context, roundRectPath);


Round Rects are Everywhere!

I continue to find it strange that Apple don't provide a function to draw a round rectangle in one line. They do provide the (more flexible) CGPathAddArcToPoint function but it lacks the simplicity of a single line function to handle the common case. Download the project and see how the implementation of NewPathWithRoundRect creates round rects using the CGPathAddArcToPoint function if you don't know how to draw round rects on the iPhone.
The absence of a round rectangle function is particularly strange given the anecdote that Andy Hertzfeld relates on and in his excellent book Revolution in the Valley. In this anecdote, Steve Jobs drags Bill Atkinson on a walk around the block with Steve pointing out how everything is made of round rects until Bill relents and agrees to put the RoundRect function into Quickdraw.
Round rectangles continue to be everywhere on the iPhone — maybe more so than on the Mac in 1984. It's a good idea to use a function like NewPathWithRoundRect in your own code.

Finding the keyboard

The keyboard on the iPhone is an instance of UIKeyboard (a private class) in its own UIWindow (actually, it may share the window with the UIAutoCorrectInlineView).
You can find the UIKeyboard with a simple search.
@implementation UIApplication (KeyboardView)

- (UIView *)keyboardView
NSArray *windows = [self windows];
for (UIWindow *window in [windows reverseObjectEnumerator])
for (UIView *view in [window subviews])
if (!strcmp(object_getClassName(view), "UIKeyboard"))
return view;

return nil;

The keyboard itself is a series of nested views which eventually reach the underlying functionality for the keys:
  • UIKeyboard
    • UIKeyboardImpl
      • UIKeyboardLayoutQWERTY
        • UIKeyboardSublayout
          • UIImageView
          • UIKeyboardSpaceKeyView
          • UIKeyboardReturnKeyView
Interestingly, the keys for the main part of the keyboard are all a single image. This arrangement probably explains why the "space" and "return" keys behave more like regular buttons than the other keys.
For the sample application, since the implementation of LoadingView will size the loading view to cover its immediate superview, passing the keyboard view fetched in this manner will create the keyboard-only loading view shown above.
If you wanted to show a full-window LoadingView that also covers the keyboard, you could pass the keyboard view's superview to the loadingViewInView: but you might want to add an extra 20 pixels padding at the top in this case, since the superview (the window) extends underneath the status bar at the top of the window.

Finding the firstResponder

While it isn't required for the sample project, I thought I'd mention how to fetch a related piece of information: the firstResponder in an iPhone application.
On the iPhone firstResponder is the view which has the current keyboard focus (or nil if no view is focussed).
This is an important piece of information, so it's strange that Apple didn't choose to provide a public method to access it. Curiously, there is a method, firstResponder, on UIWindow which returns this value but it isn't public. This will work:
UIView *firstResponder =
[[UIApplication sharedApplication]


You can see all this code and more in the sample project for this post: (129kB)
Displaying a loading view is not a very difficult task (lots of people write their own) but implementing all of the different expected behaviors is time consuming — the implementation in this post is at least 65 lines of code, depending on how you count it — so keeping a resusable implementation can save a lot of time.
Finding the keyboard and finding the current first responder on the iPhone are harder to work out since the API is hidden, and it requires a little investigative work.
Putting it all together, you could easily recreate Apple's "Sending..." progress view used in the Text program.

Cocoa With Love : Easy custom UITableView drawing

Easy custom UITableView drawing

It is really easy to customize your UITableViews. I'll show you how to completely customize the appearance of UITableViews without overriding or subclassing and without the need for any tricky hackery.

Make my table pretty

The core of most iPhone applications is the UITableView. To make your iPhone application stand out, the simplest way is to make your UITableView look good.
Customizing your UITableView can be really easy. You don't need custom drawing code. You don't need subclasses of anything. Cocoa Touch provides all the drawing capability you need, all you have to do is use the right classes in the right ways and provide the layout.

The sample application

The approach I'll show you will turn the table on the left into the table on the right:
Left: a default UITableView with three rows. Right: the same table view after customization.

How to fail at UITableView customizing

Coming from Mac OS X made it harder for me — UITableView needs to be customized in a very particular way and structurally, it is very different to Mac OS X's NSTableView and NSCell drawing.
The following are all really bad ways to customize a table (even though you can make it work):
  • Subclassing UITableView to customize drawing
  • Subclassing UITableViewCell to customize drawing
  • Creating your own array of UITableViewCells and returning these instead of using dequeueReusableCellWithIdentifier:
About the second point: it is okay to customize UITableViewCell — but you shouldn't really use it for drawing. The UITableViewCell class is more of a controller class — it handles behaviors and layout, not drawing. You can customize UITableViewCell to load a specific contentView (and do the custom drawing there).
That last point (that you should always use dequeueReusableCellWithIdentifier:) is only peripherally related to drawing but it will significantly slow your drawing down if you avoid the normal cell queuing architecture.

How to succeed at UITableView customizing

There are only a few points to understand related to table drawing.
First: the UITableView does not itself draw anything except the background. To customize the background of a UITableView, all you need to do is set its backgroundColor to [UIColor clearColor] and you can draw your own background in a view behind the UITableView.
Second: The tableHeaderView (and the table footer and section headers and footers) need not be just a title. You can insert your own view, with its own subviews in the table header, giving layout and custom drawing freedom.
Third: UITableViewCell is composed of 5 different subviews. Customizing the right subview is the secret to good UITableViewCell drawing. The subviews are:
  1. backgroundView — the entire background of the row (including what looks like the UITableView's background in UITableViewStyleGrouped style tables.
  2. selectedBackgroundView — replaces the backgroundView when the row is selected.
  3. image — a customizable image (not actually a subview) at the left of the cell.
  4. accessoryView — a customizable view at the right of the cell.
  5. contentView — a customizable view between the image and the accessoryView (technically, it extends behind the image).
You can customize any of these (except image which must be a UIImage) using your own custom drawn views.
However, since the pixel size of the table never changes, it is often easiest just to use UIImageViews for each of them. Then you can take highly complex views drawn in separate programs, cut them into the 5 necessary pieces and let the automatic caching of UIImage's named image cache manage your memory for you.
There is an argument against drawing your views in code and that is that the iPhone's drawing is not nearly as fast as Mac OS X. Operations like gradients and multiple overlapped components can really tax the iPhone.
Custom drawing code is a good choice for simple and flat colour drawing. In most other cases — as in this post — I recommend you use UIImageView to draw your views in a table.


With all custom drawing handled by UIImageView, that still leaves some work to do. You must handle all layout and configuring of views.
Configuration of the UITableView and layout of the table header
As an example of what that means, have a look at the viewDidLoad method for this post:
- (void)viewDidLoad
// Change the properties of the imageView and tableView (these could be set
// in interface builder instead).
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
tableView.rowHeight = 100;
tableView.backgroundColor = [UIColor clearColor];
imageView.image = [UIImage imageNamed:@"gradientBackground.png"];

// Create a header view. Wrap it in a container to allow us to position
// it better.
UIView *containerView =
[[[UIView alloc]
initWithFrame:CGRectMake(0, 0, 300, 60)]
UILabel *headerLabel =
[[[UILabel alloc]
initWithFrame:CGRectMake(10, 20, 300, 40)]
headerLabel.text = NSLocalizedString(@"Header for the table", @"");
headerLabel.textColor = [UIColor whiteColor];
headerLabel.shadowColor = [UIColor blackColor];
headerLabel.shadowOffset = CGSizeMake(0, 1);
headerLabel.font = [UIFont boldSystemFontOfSize:22];
headerLabel.backgroundColor = [UIColor clearColor];
[containerView addSubview:headerLabel];
self.tableView.tableHeaderView = containerView;
This method handles the configuration of the tableView (setting the backgroundColor, rowHeight and sets an image behind the table) but also creates its own layout for the table header.
The layout of the header here is for the table's header view. You can include a custom header for every table section by implementing the UITableViewDelegate method tableView:viewForHeaderInSection:. There are equivalent properties and methods for the table and section footers.
It is possible to handle this type of layout in Interface Builder and load the XIB files for this type of layout. Sadly though, on the iPhone, reading loading lots of views from XIB files is slow (I suspect this is due to slow reading from the Flash memory) and doesn't always allow configuration of every property.
For this reason, I normally sketch my views in Interface Builder and then manually recreate the same thing in code. That's what I've done here: picking coordinates for the headerLabel that looks balanced in the view.
Cell backgrounds
The cell background needs to incorporate the tops and bottoms of table "sections". For this reason, the backgroundView and selectedBackgroundView normally need to be set on a row-by-row basis.
In your tableView:cellForRowAtIndexPath: method where you are configuring the cell for a given row, this code will handle that behavior:
UIImage *rowBackground;
UIImage *selectionBackground;
NSInteger sectionRows = [aTableView numberOfRowsInSection:[indexPath section]];
NSInteger row = [indexPath row];
if (row == 0 && row == sectionRows - 1)
rowBackground = [UIImage imageNamed:@"topAndBottomRow.png"];
selectionBackground = [UIImage imageNamed:@"topAndBottomRowSelected.png"];
else if (row == 0)
rowBackground = [UIImage imageNamed:@"topRow.png"];
selectionBackground = [UIImage imageNamed:@"topRowSelected.png"];
else if (row == sectionRows - 1)
rowBackground = [UIImage imageNamed:@"bottomRow.png"];
selectionBackground = [UIImage imageNamed:@"bottomRowSelected.png"];
rowBackground = [UIImage imageNamed:@"middleRow.png"];
selectionBackground = [UIImage imageNamed:@"middleRowSelected.png"];
((UIImageView *)cell.backgroundView).image = rowBackground;
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
Layout within the contentView
Layout of elements within the contentView need only be set on construction of the contentView (not on a row-by-row basis).
Sadly, laying out UILabels in the contentView (like the "Cell at row X." and "Some other infomation." lables in this example) is a little verbose.
The following code is run immediately after the allocation of the UITableViewCell to position the "Cell at row X." label:
const CGFloat LABEL_HEIGHT = 20;
UIImage *image = [UIImage imageNamed:@"imageA.png"];

// Create the label for the top row of text
topLabel =
[[[UILabel alloc]
image.size.width + 2.0 * cell.indentationWidth,
0.5 * (aTableView.rowHeight - 2 * LABEL_HEIGHT),
aTableView.bounds.size.width -
image.size.width - 4.0 * cell.indentationWidth
- indicatorImage.size.width,
[cell.contentView addSubview:topLabel];

// Configure the properties for the text that are the same on every row
topLabel.tag = TOP_LABEL_TAG;
topLabel.backgroundColor = [UIColor clearColor];
topLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
topLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];

// Create a background image view.
cell.backgroundView = [[[UIImageView alloc] init] autorelease];
cell.selectedBackgroundView = [[[UIImageView alloc] init] autorelease];
In my mind, it seems like there should be a more efficient way to do this. I hold out the possibility that there is.
This code spends most of its time working out where the label should be placed. It needs to go right of the image, left of the accessoryView, middle of the row but above the "Some other information." label.
Other adornments
The accessoryView is just a UIImageView. The cell.image is set as a property. These are extremely simple additions but they make the table cells far more impactful.


You can download the EasyCustomTable project as a zip file (60kb).
The code includes a #define at the top that allows you to toggle the custom drawing on and off.
None of this is particularly revolutionary (it is all in the iPhone documentation) but it is still easy to miss the properties and methods that make it easy.

Tuesday, June 1, 2010

iPhone Development Tutorial - Cocos2d Circle to Circle Collision Detection

01- (BOOL) circle:(CGPoint) circlePoint withRadius:(float) radius collisionWithCircle:(CGPoint) circlePointTwo collisionCircleRadius:(float) radiusTwo
03 float xdif = circlePoint.x - circlePointTwo.x;
04 float ydif = circlePoint.y - circlePointTwo.y;
06 float distance = sqrt(xdif*xdif+ydif*ydif);
08 if(distance <= radius+radiusTwo) return YES;
10 return NO;

Get Twitter Fan Box Widget

Like Us On Facebook and Receive All Updates!

You can also receive Free Email Updates:

Powered By Tutorails