I have a button that is created dynamically and needs to be resized. It has plenty of space where to grow but calling sizeToFit seams to do nothing or at least not enlarging the button enough.
How can I obtain the desired effect?
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;
(written from memory; not compiled. :-)
Of course, you have to set the button title and font as well...
In iOS 7, sizeWithFont: is depreciated. Now you should use sizeWithAttribute:.
But that's not how I would solve this issue. There are two ways you can go about it:
1) To use [button sizeToFit] make sure AutoLayout is disabled. Otherwise, you won't be able to adjust the size of your button programmatically. You'll have to adjust the size of your constraints.
2) However, this answer is very limited in is use. In the example I'm about to show you, the button would go off the screen because the text is all on one line. To change the height of your button while constraining the width use the following code. Once again make sure autolayout is turned off or this will not work.
UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:14.0];
NSString *text = @"This is a very long new title for the button to be sure, now I'm going to add even more";
[self.testButton setTitle:text forState:UIControlStateNormal];
self.testButton.titleLabel.font = font;
CGFloat width = self.testButton.frame.size.width - 10; //button width - padding width
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
size.height = ceilf(size.height);
size.width = ceilf(size.width);
self.testButton.frame = CGRectMake(self.testButton.frame.origin.x, self.testButton.frame.origin.y, self.testButton.frame.size.width, size.height + 15);
Because boundingRectWithSize will pass you a rect that has non-integer sizes you have to use ceilf to round up.
I subtract 10 from the width before I pass it into boundingRectWithSize to create padding for my button.