Resize a UIBarButtonItem when the title gets too wide
<p>Some background: I wanted to have 3 buttons on a <code>UIToolBar</code>. I managed to get the middle one centered and everything by putting it into a <code>UIToolBar</code> itself into a <code>UIView</code>. </p>

<p>Everythings looks just like it should apart from when the title of the middle buttons gets too big.
It then gets displayed under the left or right buttons.</p>

<p>I can't get the <code>UIToolBar</code> or the <code>UIBarButtonItems</code>'s width to be able to resize them when they're too big.
The 'UIBarButtonItem' has a really nice <code>width</code> property that would allow me to resize the control if it's too big.
But I can't know when it's too big!</p>

<p>EDIT: I did the hard way in the end. I calculate the size of the text and compare it to the maximum pixel size I saw fit on the device. Ugly but it works.</p>

<pre><code>+ (CGFloat)calculateTextWidth:(NSString *)text
{
    CGSize fullSize = [UIScreen mainScreen].applicationFrame.size;
    UIGraphicsBeginImageContext(fullSize);

    CGContextRef context = UIGraphicsGetCurrentContext();


    // calculate the text size
    CGContextSelectFont(context, "Helvetica", 17, kCGEncodingMacRoman);
    CGContextSetTextMatrix(context, CGAffineTransformMakeScale(1.0, -1.0));
    CGContextSetTextDrawingMode(context, kCGTextInvisible);

    // measure the text
    CGPoint initialTextPosition = CGContextGetTextPosition(context);
    CGContextShowTextAtPoint(context, 0, 0, [text cStringUsingEncoding:NSASCIIStringEncoding], text.length);
    CGPoint finalTextPosition = CGContextGetTextPosition(context);

    return finalTextPosition.x - initialTextPosition.x;
}
</code></pre>
