Some background: I wanted to have 3 buttons on a UIToolBar
. I managed to get the middle one centered and everything by putting it into a UIToolBar
itself into a UIView
.
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.
I can't get the UIToolBar
or the UIBarButtonItems
's width to be able to resize them when they're too big.
The 'UIBarButtonItem' has a really nice width
property that would allow me to resize the control if it's too big.
But I can't know when it's too big!
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.
+ (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;
}