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;
}
Put a Flexible Space Bar Button Item between the left and right buttons and the centre button; that will allow the side buttons to take up only as much width as they need and keep the centre button centred whilst allowing it to grow into the space around it.
Here's a couple of screenshots from Interface Builder of something I was working on this morning that shows the effect: the double-headed arrows are IB's way of showing the flexible space items...
...and the same with a longer title on the centre button...
and here's the toolbar with short and long centre button as seen on my iPhone 3GS:
Here is a better way to find the text width:
+ (CGFloat)calculateTextWidth:(NSString *)text
{
UIFont *font = [UIFont fontWithName:@"Helvetica" size:17];
return [text sizeWithFont:font].width;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With