Automatically resizing UIButton height based on title - AutoLayout ON

感情迁移 提交于 2019-12-10 11:57:15

问题


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)];


来源:https://stackoverflow.com/questions/22455099/automatically-resizing-uibutton-height-based-on-title-autolayout-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!