问题描述
基本上标题解释该问题。与X code工作,我有这样的按钮,我填充其具有不同的文本源(有些是长文本一些短)的标题。我只是想,按钮使用自动布局内容动态调整。
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.
东西不工作:
-
sizeToFit
; - 设置高度> = x的约束;
- 设置按钮的架高度= titleLabel高度。
似乎没有人知道在互联网上,我不知道它怎么可能呢?我认为这是一个按钮的最常用的功能之一。
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.
推荐答案
好吧,我发现这个解决方案:
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];
这工作,但只有一次。我的意思是:只要新标题填充titleLabel它说,已经有一个约束,它不工作了...
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...
这篇关于自动调整高度的UIButton基于标题 - 自动版式ON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!