Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

RossOliver

macrumors regular
Original poster
Nov 6, 2006
157
0
Hey,

I need the text that is set as the title to a UIButton to automatically shrink/enlarge to fit the button area (like adjustsFontSizeToFitWidth does for UILabel). I notice that the text view on a UIButton is a UILabel, but it is private so I can't subclass it/change it to enable this property.

What's the best way to go about achieving this? At the minute all I can think of is to subclass the UIButton, make a new UILabel instance variable and override all methods that interact with the default UIButton text view...

I guess I could also just have a UILabel sit on top of a UIButton and set the text of the UILabel directly instead of the button, but that seems like a bit of a dodgy workaround...

Thanks for your time,

-Ross
 
Use the sizeWithFont... methods (UIStringDrawing.h) to determine the size of the string using the button's font. Then resize the button using this size, plus any needed padding.
 
Use the sizeWithFont... methods (UIStringDrawing.h) to determine the size of the string using the button's font. Then resize the button using this size, plus any needed padding.

You may have misunderstood what I'm after (or I may have misunderstood you). I don't want to resize the button, but the text inside the button...

Did you mean to get the size of the string using the buttons font, then resize the string to that of the button + any padding? That sounds plausible to me - thanks for the idea, I shall give it a go a little later on!

-Ross

Actually, after re-reading my original post I didn't specify which one I wanted to shrink/expand - but it looks like both the button and text could be resized using your method :)
 
Having looked at this further, it would appear you can expand the button size to match the text since you can get the text width for the button font and then redraw the button with an altered CGRect using the new text width.

However, the other way around is giving me problems. Is there any way to specify a font size that will confine the font to a specific CGRect width?

Thanks for your time,

-Ross

[edit]

Achieved what I needed using a loop - not very clean but does the job...

Code:
	while( textWidth > titleWidth )
	{
		[myButton setFont:[[myButton font] fontWithSize:--originalButtonFontSize]];
		textWidth = [text sizeWithFont:[myButton font]].width;
	}

Can anyone think of a better method?
 
valid for iPhone OS 3.0

Code:
- (void)viewDidLoad {
    [super viewDidLoad];
	
    myButton.titleLabel.adjustsFontSizeToFitWidth = TRUE;
}
 
Last edited by a moderator:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.