0

I put a default button in the Interface builder, and it has some default size

then I programmatically changed its title, and received this:

enter image description here

this is my code for this button:

 NSString *btnGetRegisterCodeTitle = NSLocalizedString(@"Get Registration Code", @"Title on button");
[_btnRegister setTitle:btnGetRegisterCodeTitle forState:UIControlStateNormal];

What do i need to do to the button, to make it autolayout its frame so that the entire (3 words ) title would fit on it?

Lena Bru
  • 13,521
  • 11
  • 61
  • 126

3 Answers3

0

after changing the title call sizeToFit

[yourButton sizeToFit];
thorb65
  • 2,696
  • 2
  • 27
  • 37
0

What exactly happening here is, When you are changing the title of button, the text becomes out of bound. What you can do is, programmatically set the button size to fit its content/title.

For that use this:

NSString *btnGetRegisterCodeTitle = NSLocalizedString(@"Get Registration Code", @"Title on button");
[_btnRegister setTitle:btnGetRegisterCodeTitle forState:UIControlStateNormal];
[_btnRegister sizeToFit];

Here the sizeToFit method will automatically resize your UIButton in such a way that your Title is not merged/overlapped.. :)

Update:

Have a look at this Question

I've copied the selected answer from there, in case that question is removed..

Check out the NSString method -sizeWithFont:. It returns a CGSize that will inform you as to how much size your text will need in the button. Then you can adjust the button's frame based on this size, adding whatever padding you desire to the width and height of the button's frame. Something like this:

NSString *msg = @"The button label";
UIFont *font = [UIFont systemFontOfSize:17];
CGSize msgSize = [msg sizeWithFont:font];
CGRect frame = button.frame;
frame.size.width = msg.size.width+10;
frame.size.height = msg.size.height+10;
button.frame = frame;
Community
  • 1
  • 1
Prince Agrawal
  • 3,619
  • 3
  • 26
  • 41
  • Unfortunately, this does not change the way the button looks, i added the line sizeToFit, and the button looks the same – Lena Bru Jan 29 '14 at 15:46
0
NSString *btnGetRegisterCodeTitle = NSLocalizedString(@"Get Registration Code", @"Title on button");
CGSize size = [btnGetRegisterCodeTitle sizeWithFont:_btnRegister.titleLabel.font];
[_btnRegister setTitle:btnGetRegisterCodeTitle forState:UIControlStateNormal];
_btnRegister.frame = CGRectMake(_btnRegister.frame.origin.x, 
                                _btnRegister.frame.origin.y,
                                size.width, size.height);

How about this one? It is practically the same answer as above, just more simple so you won't get it wrong by mistake. (Using the button title's font instead of system font). You can still try to add the 10 points to width and height like in the previous answer if you want.

Naor Levi
  • 117
  • 7