James Dunay
James Dunay

Reputation: 2724

Scaleable buttons in objective-c

I was wondering if its possible, and how i might do the following,

I would like to have a UIButton, a simple rounded button with one color, but i would like to have it's width scaleable based upon the UILabel that is on the inside of it.

I found somethings that talked about how it's possible to use

UItextfield

and use the .leftView and .rightView properties that it has

Could anyone give me just a quick example of how i might do this?

Thanks!

Upvotes: 1

Views: 408

Answers (2)

James
James

Reputation: 2282

I assume that the text of the UILabel will by dynamic, so you cannot just figure out the dimensions and add them normally?

try this:

-(void)setLabelText:(NSString*)string
{
   int length = string.length;

   myLabel.frame = CGRectMake(x, y, 5*length+5, height);
   buttonContainingLabel.frame = CGRectMake(x, y, 25+5*length, height);
}

This method assumes a monospaced font, which you are probably not using. Still, discrepancies in character width probably won't amount to any meaningful size differential as you are not writing a novel in the button. I use the value of 5 px here as the width of a letter, but you will have to modify this to fit your text size.

Upvotes: 0

johnbakers
johnbakers

Reputation: 24770

You can find the size of the NSString in the UILabel by doing something like this:

CGSize size=[uibutton.titlelabel.text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:fontSize] forWidth:uibutton.titlelabel.frame.size.width lineBreakMode:UILineBreakModeCharacterWrap];

Then set the frame of the uilabel and/or uibutton using this size.width and size.height properties.

This is just an example, you will need to adjust the UIFont properties based on your label's settings or preferences.

Upvotes: 2

Related Questions