Edward Hasted
Edward Hasted

Reputation: 3433

UIButton resizing to fit text length

There are a number of posts on Stack about this subject but I can't get any to work.

I have a Button whose text literal is supplied by a variable which can change in length. I want the button to be sufficiently long so the text is readable rather than concatenated in the middle with ".....".

If I use something like

CGSize stringsize = [myString sizeWithFont:[UIFont systemFontOfSize:15]];
NSLog(@"Width = %f", stringsize.width);
[myButton setFrame:CGRectMake(20,0,stringsize.width, stringsize.height)];

Similarly I have been unable to get commands like to work either.

[self myButton sizeToFit];

Does anyone have a solution that does work?

I am trying to implement these from viewDidLoad.

Upvotes: 1

Views: 691

Answers (2)

Yitzchak
Yitzchak

Reputation: 3416

Answer for Xcode 7.2

Click on the view that needs the fit (Not from the list of views from the left panel, but in the stage itself)

Now click on Editor menu, and then Size to Fit Content

Voila!!

You can use the shortcut command + =

Upvotes: 0

Max Strater
Max Strater

Reputation: 538

Are you using a storyboard? If so, go to your file inspector in the storyboard and see if you have "use autolayout" checked. From what I can tell, uibuttons won't respond to frame changes while this option is checked.

Upvotes: 2

Related Questions