Uibutton That Resizes to Fit Its Titlelabel

UIButton that resizes to fit its titleLabel

I've gotten this to work, but you have to use a custom button, not a system type. Give the button both width and height constraints, and make an IBOutlet to the height constraint (heightCon in my code) so you can adjust it in code.

- (void)viewDidLoad {
[super viewDidLoad];
self.button.titleLabel.numberOfLines = 0;
self.button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[self.button setTitle:@"A real real real real real real real real long long name." forState:UIControlStateNormal];
[self.button addTarget:self action:@selector(doStuff:) forControlEvents:UIControlEventTouchUpInside];
self.button.backgroundColor = [UIColor redColor];
self.button.titleLabel.backgroundColor = [UIColor blueColor];
[self.button layoutIfNeeded]; // need this to update the button's titleLabel's size
self.heightCon.constant = self.button.titleLabel.frame.size.height;
}

After Edit:

I found that you can also do this more simply, and with a system button if you make a subclass, and use this code,

@implementation RDButton

-(CGSize)intrinsicContentSize {
return CGSizeMake(self.frame.size.width, self.titleLabel.frame.size.height);
}

The overridden intrinsicContentSize method is called when you set the title. You shouldn't set a height constraint in this case.

Swift 5 : Resizing a button according to titleLabel length with padding

Couple things...

  • on your stack view, set .distribution = .fill instead of .equalSpacing. You have only two arranged subviews (there's only one space)
  • you shouldn't need myButton.sizeToFit()

Add this line to your button setup:

myButton.setContentCompressionResistancePriority(.required, for: .horizontal)

That should prevent your button from compressing / truncating its label.

How do I resize a UIButton to fit the text without it going wider than the screen?

I managed to get it working in a category of UIButton:

@interface UIButton (ExpandsVertically)

- (CGSize)sizeThatFits:(CGSize)size;

@end

@implementation UIButton (Expandable)

- (CGSize)sizeThatFits:(CGSize)size {

// for the width, I subtract 24 for the border
// for the height, I use a large value that will be reduced when the size is returned from sizeWithFont
CGSize tempSize = CGSizeMake(size.width - 24, 1000);

CGSize stringSize = [self.titleLabel.text
sizeWithFont:self.titleLabel.font
constrainedToSize:tempSize
lineBreakMode:UILineBreakModeWordWrap];

return CGSizeMake(size.width - 24, stringSize.height);
}

@end

If anyone uses this make sure to set:

myButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;

How to resize UIButton's titleLabel

plaese use below code

let label = self.button?.titleLabel
label?.minimumScaleFactor = 0.01
label?.adjustsFontSizeToFitWidth = true
label?.font = UIFont.systemFontOfSize(100)


Related Topics



Leave a reply



Submit