Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize a UIBarButtonItem when the title gets too wide

Tags:

iphone

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;
}
like image 301
R4cOOn Avatar asked Nov 18 '10 13:11

R4cOOn


2 Answers

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...

Interface Builder screenshot showing toolbar with wide flexible spaces

...and the same with a longer title on the centre button...

Interface Builder screenshot showing toolbar with narrow flexible spaces

and here's the toolbar with short and long centre button as seen on my iPhone 3GS:

iPhone screenshot showing toolbar with wide flexible spaces

iPhone screenshot showing toolbar with narrow flexible spaces

like image 144
NickFitz Avatar answered Nov 02 '22 13:11

NickFitz


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;
}
like image 2
cduck Avatar answered Nov 02 '22 12:11

cduck