Creating a 0.5px Hairline in iOS7

Since iOS7 UITableViews have seen a new design. The separator line now has a customizable inset and is only 0.5px thin (on retina devices) – just a hairline!

The entire new OS design actually heavily relies on hairlines, delimiting navigation and tab bars for example.
As a designer, you’ll want to hop onto the design trend and not use a table view for everything, question is how do you create the hairline as a developer?
Setting the width or height of a UIView to 0.5 in your code will only make the thing invisible and in a Storyboard you can’t do it anyway.

I started fumbling around and figured it’s not that hard when you use borders!

Assuming you do your layouts with Storyboards

Place an UIView with your desired height and 1px width (for a vertical line) or desired width and 1px height (for a horizontal line) into your layout. Give it whatever background color you’d like it to have. The standard separator color is approx. RGB(200,199,204).

Then create a subclass of UIView, e.g. HairlineView and override awakeFromNib()

-(void)awakeFromNib {
    self.layer.borderColor = [self.backgroundColor CGColor];
    self.layer.borderWidth = (1.0 / [UIScreen mainScreen].scale) / 2;

    self.backgroundColor = [UIColor clearColor];
}

You’re drawing a border around your 1px wide view, which is 2 * 0.25px wide making it 0.5px in total, which is the width you wanted to achieve, then hide the background of the view by making it transparent.
This last step is important, it won’t work without.

Adjust the type of your view to HairlineView in the Storyboard. You should see the result once you run the app.

When doing it programmatically, you’d have to override a different method, e.g. initWithFrame() maybe, since awakeFromNib() only gets called when you create the view from a Storyboard layout, haven’t tried that yet though…