Wednesday, 21 November 2012

BVUnderlineButton - iOS Control for web-link style button

My client requested a web-link style button for a forgot password button on the log-in screen, which seemed on the surface to be a simple thing to implement.

After looking into it I was surprised to learn that there's no built-in way to underline text in a UI element on iPhone - you have to simply draw it yourself.

Searching the web I found some sample code in varying states of usability. By sticking these together and putting a couple more features in I came up with CVUnderlineButton.

It's available on GitHub at

Simple example button

Here's the README for the control.


Simple UIButton subclass that draws a button with the title underlined.
Based on code originally found at with all the fixes from the comments and some further tweaks.
This code requires ARC.


Add BVUnderlineButton.m and BVUnderlineButton.h to your project.
If you're using a Storyboard or XIB files:
  • drag a UIButton to your stage, set the 'Type' (under Attributes Inspector / Button) to Custom
  • Set the Class (under Identity Inspector / Custom Class) to BVUnderlineButton.
If you're using code, just create the button as you would a regular Custom style UIButton, e.g.
#import "BVUnderlineButton.h"

BVUnderlineButton *button = [BVUnderlineButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self 
[button setTitle:@"underlined" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
Adjusting the underline position

Depending on the font you may wish to adjust the vertical position of the underline using the underlinePosition property. The default is -2 pixels.
If you're using a Storyboard or XIB files:
  • Select the BVUnderlineButton instance on your stage.
  • Open the 'Identity Inspector' and click the + under 'User Defined Runtime Attributes'
  • Type 'underlinePosition' for keyPath, choose 'Number' for type, and type in the new value as a floating-point number (e.g. 1)
If you're using code, just set the underlinePosition property.
button.underlinePosition = 1;

Wednesday, 14 November 2012

RestKit: Could not find an object mapping for keyPath: ' '

RestKit is an excellent Objective-C framework to make dealing with downloading and uploading data to and from a REST-based server considerably simpler than coding it all yourself.

When I started out I found it pretty straightforward until I hit a REST command that returned a JSON array at the root object, where I ran into the dreaded Could not find an object mapping for keyPath: ' ' error.

Here's an example REST response that caused this error:

[ { "name":"foo"}, { "name":"bar"} ]

It seems restkit expects there to be a root level object e.g. 

{ "data": [ { "name":"foo"}, { "name":"bar"} ] }

If your server doesn't do this, and you can't change it, then the automatic mapping system doesn't seem to work.

The solution is pretty simple (manually tell the system which mapping to use) but I took me a while to figure out, so I thought it might help others if I posted it here.

Wednesday, 19 September 2012

Making apps work on iPhone 5 screen size

Here's a series of gotchas I found in attempting to convert my apps to work correctly on the new taller screen of the iPhone 5.

You need to add a new splash screen at the iPhone 5 size.

This is easy. Just create a new splash screen that's exactly 640x1136 pixels in size.
Call it Default-568h@2x.png and include it in your app.

The existence of this file is the magic key that tells iOS6 that your app is ready for iPhone 5. Without this file your app will always appear bordered.

Use window.rootViewController to add your initial view

First up, if you're building your initial views in code make sure you add your initial view to the window with window.rootViewController rather than the old way of simply adding the view as a subview.
If you don't do this, autorotating will not work at all for your app under iOS 6.

Here's an example:

navigationController = [[UINavigationController alloc] initWithRootViewController: myRootVC];
//[window addSubview:[navigationController view]]; Don't do this!
window.rootViewController = navigationController; // Do this instead!

Use viewDidLayoutSubviews rather than viewDidLoad to set up widget sizes relative to the window

If you lay out your UI in Interface Builder, and set the struts and springs properly, you might expect that inside your viewDidLoad method, your widgets will be auto-laid out to the new taller size.
They won't be! Everything will be exactly the size that you set it to be in Interface Builder at that stage.
As a result you should make sure you don't depend on the size of a widget in the viewDidLoad method. I hit this when I wanted to programatically create a view half the height of the screen.

Of course, by the time the user sees the screen everything is the right size. The issue is that this resizing takes place after the viewDidLoad - but where?

The answer is to use the viewDidLayoutSubviews method which is called after the automatic layout has finished. Override this method and insert your custom sizing.

- (void) viewDidLayoutSubviews
    // do clever layout logic here. super call not needed.
Automatically loading iPhone 5-sized images where required

You'll be familiar with the way that [UIImage imageNamed:] automatically loads @2x versions of images when running on a retina device.  Unfortunately, imageNamed: will NOT automatically load -586h@2x versions of images when running on an iPhone 5.

Sometimes this doesn't matter, for example icons and non-full screen graphics are probably the same on iPhone 4 & 5. However, if you have full-screen background images, or full-width / height background images for toolbars etc you will have problems. Your 480-high images will most likely get stretched (and will probably look horrid as a result).

You can manually check the screen size and load the right image like this:

UIImage* myImage;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
if ([UIScreen mainScreen].scale == 2.f && screenHeight == 568.0f) {
   myImage = [UIImage imageNamed:@"myImage-568h@2x.png"];
} else {
   myImage = [UIImage imageNamed:@"myImage.png"];

Or better you can 'swizzle' the imageNamed function itself, and make it automatically pick up the right image (if available).
Here's an example I found on github to do exactly this (I did not write this code, copyright is with the author).

currentTime not working with the HTML5 Audio tag.. a solution!

Today I've been using the HTML5 Audio tag (in fact actually just the JavaScript Audio() object). I ran into a number of issues where clearly-documented functions simply didn't work.

Here's some sample code, with XXXXs marking what wasn't working for me (in any browser).

Now it turns out the reason these functions didn't work is not that browsers suck and this whole HTML5 is hugely overrated (my initial reaction), but was in fact that the server serving the MP3 files did not support streaming. Of course if would have been nice if somehow the audio object would warn me about this rather than sitting there doing nothing, but you can't have everything.

Anyway, now the question was how do I make my server support streaming? Do I need to sign up for some kind of premium service? Or spend weeks implementing a streaming sever?

Thankfully not. It turns out you 'simply' need to make your server support HTTP Range requests. If your server uses PHP, you're in luck. I've got a complete working example which I can share with you right now.

Note I did not write this code, I found it here and added it to gist for posterity.

Simply add this code to your PHP server, and when you're about to serve an MP3 (or OGG or whatever) call this function.

For reference, I call the function like this (where $fullPath is the absolute path to my MP3 Resource).

smartReadFile($fullPath, basename($fullPath), 'audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3');

Tuesday, 21 August 2012

OSX Terminal: alt-left jump word ctrl-left go to start and more

By default OSX Terminal doesn't let you use many standard OSX text-editing shortcuts. For example, CMD or Control Left normally jumps to the start of the line. Alt-left jumps left one word. Also forward delete doesn't work.

Happily it's possible, though slightly confusing, to add these shortcuts back.

Here's how:
  • Open Terminal Preferences
  • In the Settings Pane, select Keyboard

  • Click the + button

  • Now let's add those shortcuts back.
For jump-to-start-of-line:
  • Key: Cursor Left
  • Modifier: Control
  • Action: send string to shell: (the default)
  • Click in the empty white box and press CTRL-A. \001 will appear
For jump-to-end-of-line:
  • Key: Cursor Right
  • Modifier: Control
  • Action: send string to shell: (the default)
  • Click in the empty white box and press CTRL-E. \005 will appear
To re-activate forward delete
  • Key: forward delete
  • Modifier: none
  • Action: send string to shell: (the default)
  • Click in the empty white box and press CTRL-D. \004 will appear
To move forwards one word at a time
  • Key: cursor left
  • Modifier: option
  • Action: send string to shell: (the default)
  • Click in the empty white box and press Escape+b. \033b will appear
To move backwards one word at a time
  • Key: cursor right
  • Modifier: option
  • Action: send string to shell: (the default)
  • Click in the empty white box and press Escape+f. \033f  will appear.

I find adding these shortcuts in makes terminal much more usable. 

Friday, 17 August 2012

Editing a Phonegap app directly on your device without reinstalling or rebuilding

How often have you built a large Phonegap app, copied it to your device, played with it for a while and then discovered a tiny bug? Something that you just know is just a single line, or even a single character change...

Normally to test your fix you'd need to make the change in your IDE, and re-build and re-upload the app to your device using Xcode. This can take ages if your app has a lot of content.

If you're using Phonegap build, it can take even longer as you'll have to wait for the whole app to build and then download again.  This can be particularly painful if your one line change takes a few goes to get right (especially anything UI or animation-related).

So what's the solution? Well, it's actually possible to connect your iPhone to your Mac, edit your JS file (or any other file) and re-save, and run the app again.

I was surprised to discover that this is possible - I'd assumed the code signing verification system built into the iDevice would notice that the bundle had changed and refuse to run but it doesn't. At least not in my experience.

Here's how to do it (note commercial software required, though the demo does actually work. I don't work for them and am not paid!)

  • A new drive will appear. Open it.
  • Inside you'll see a bundle, e.g. com.example.myapp.
  • Right-click the bundle and choose 'view package contents'

  • Open the www folder (or whichever folder your app uses for PhoneGap content)

  • Open the JS file you want to change in your favourite text editor (we use Sublime Text
  • Save changes. This writes it straight back to the device!
The above instructions are for Mac, but I suspect pretty much the same process will work for PC too.

Now you can re-start your app and the new code should be live! 

This technique works for HTML, JavaScript, CSS and other text files. It most likely won't work with PNG files as the app build process compresses them into a proprietary Apple format (you can convert, but it is fiddly). I haven't tried JPG, MP4, files etc. Your milage may vary.

Dealing with Cacheing issues

Note that quite regularly you'll find the iDevice still runs the old version of your JS file. This is due to the UIWebView caching the JS file.

The easier way to fix this is to force the iDevice to reload the Javascript file by changing the link to the JS file.   To do this, edit your main HTML file using the technique above.

Change the link from (for example)

<script src="myfile.js" type="application/javascript"></script>


<script src="myfile.js?_cache=123" type="application/javascript"></script>

Each time you change the myfile.js, also update the _cache=123 number and you'll always get the latest version. _cache doesn't actually mean anything, you can choose whatever you want.

A kaleidoscope built using (almost) pure CSS3

Here's a kaleidoscope made using pure CSS3. Ok, almost pure CSS.
The only bit of JavaScript is used to kick off the animations. I could have done this is CSS too, but ran out of time.
The way it works is there's a 500px square div containing a triangular -webkit-mask-image (defined by the SVG file). This mask image ensures that regardless of the size and position of the background image, you only ever see a triangular shaped section. You can think of it as a 'cutout'.
This div is duplicated, flipped and rotated eight times to create the effect. We then animate the resulting 'scope by simply moving the position of the background image.
I think it's quite neat. Unfortunately this fairly simple page actually crashes iPad and iPhone devices running (at least) 5.1.1 after a while. Very frustrating!

View Demo

Source Code