Code Example: Drawing the iPhone Back Button

Recently, I had need to provide a back button similar to the one used in Mobile Safari for a consulting project.

Many of the buttons used in the built-in iPhone applications are made available via the SDK with built in button types and graphics. Unfortunately, the back button is not one of these.

Because I needed to display the toolbar button from inside a static library which can not include images, I had to render the back arrow directly in code.

Since this was a bit time consuming, I thought I would share in hopes that it saves someone else a little bit of time.

- (CGContextRef)createContext
   // create the bitmap context
   CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
   CGContextRef context = CGBitmapContextCreate(nil,27,27,8,0,
   return context;

- (CGImageRef)createBackArrowImageRef
   CGContextRef context = [self createContext];
   // set the fill color
   CGColorRef fillColor = [[UIColor blackColor] CGColor];
   CGContextSetFillColor(context, CGColorGetComponents(fillColor));
   CGContextMoveToPoint(context, 8.0f, 13.0f);	
   CGContextAddLineToPoint(context, 24.0f, 4.0f);
   CGContextAddLineToPoint(context, 24.0f, 22.0f);
   // convert the context into a CGImageRef
   CGImageRef image = CGBitmapContextCreateImage(context);
   return image;

- (UIBarButtonItem *)backButton
   CGImageRef theCGImage = [self createBackArrowImageRef];
   UIImage *backImage = [[UIImage alloc] initWithCGImage:theCGImage];
   UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:backImage
   [backImage release], backImage = nil;
   return [backButton autorelease];

One thought on “Code Example: Drawing the iPhone Back Button

  1. Nice! This works beautifully. Only one bit of feedback: You may need to use “new” instead of “create” in those first two method names, as they both return objects that aren’t autoreleased. Otherwise, the static analyzer will raise the proverbial red flag.

Comments are closed.