Automatically resizing UIButton height based on ti

2019-06-09 15:34发布

问题:

Basically the title explains the problem. Working with XCode, I have this button and I populate its title with different text sources (some are long texts some are short). I just want that the button resizes dynamically with the content using Autolayout.

Things not working:

  • sizeToFit;
  • Setting a height constraint of >= x;
  • setting the button's frame height = titleLabel height.

Nobody seems to know over the internet and I wonder how could it be possible? I think is one of the MOST COMMON FEATURES for a button.

Someone knows a way to help me? Am I doing something wrong with this idea? Is there some other way to achieve this?

Thank you to anyone who will answer. Really.

回答1:

Ok i found this solution:

NSAttributedString *text = [[NSAttributedString alloc] initWithString:[self titleForState:UIControlStateNormal] attributes:nil];

CGRect rect = [text boundingRectWithSize:(CGSize){287, CGFLOAT_MAX}
                                                 options:NSStringDrawingUsesLineFragmentOrigin
                                                 context:nil];


NSLayoutConstraint *buttonConstraint = [NSLayoutConstraint
                                    constraintWithItem:self
                                    attribute:NSLayoutAttributeHeight
                                    relatedBy:NSLayoutRelationEqual
                                    toItem: nil
                                    attribute:NSLayoutAttributeNotAnAttribute
                                    multiplier:1.0f
                                    constant:rect.size.height];

[self addConstraint:buttonConstraint];

Which works but ONLY ONE TIME. I mean: as soon as the new title populates the titleLabel it says that there is already a constraint and It doesn't work anymore...



回答2:

you can do like this

CGSize stringsize = [myString sizeWithFont:[UIFont systemFontOfSize:14]]; 
//or whatever font you're using
[button setFrame:CGRectMake(10,0,stringsize.width, stringsize.height)];