可以让 UIButton sizeThatFits 工作吗?

Posted

技术标签:

【中文标题】可以让 UIButton sizeThatFits 工作吗?【英文标题】:Possible to get UIButton sizeThatFits to work? 【发布时间】:2015-03-16 22:44:01 【问题描述】:

我一直在使用一种调整 UIButton 大小的方法,该方法已被折旧,并且不是很健壮。出于这个原因以及其他原因,我想让 sizeThatFits 为 UIButtons 工作。根据我在网上阅读的内容,我不确定它是否应该工作(似乎它适用于某些人,但不适用于其他人,可能风格之间的差异,我使用的是自定义)。

这是我重新创建问题的简单测试代码(我只是将它放在 viewDidLoad 中进行测试,但没关系,我的真实代码是一个大型项目的一部分):

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:@"This is a test with a long title that will need to word wrap to more than a single line when displayed on my tiny iPod in portrait view." forState:UIControlStateNormal];
btn.titleLabel.lineBreakMode = UILineBreakModeWordWrap; // depreciated - but nothing to replace it?
CGRect r = btn.frame;
r.origin.x = 0;
r.origin.y = 0;
r.size.width = 320;
r.size.height = [btn.titleLabel.text sizeWithFont:btn.titleLabel.font constrainedToSize:CGSizeMake(r.size.width,100000) lineBreakMode:btn.titleLabel.lineBreakMode].height; // Returns approx 86 and changes correctly if I change the title text
r.size.height = [btn sizeThatFits:CGSizeMake(r.size.width,CGFLOAT_MAX)].height; // returns 34 no matter what
btn.frame = r;

sizeWithFont 行是我一直在做的,它可以工作,但它并没有要求实际控制大小,所以不是很安全,也被贬值了。 sizeThatFits 行是我想要使用的,但无论如何它总是返回 34(可能是按钮的推荐/默认高度)。

我一直在使用相同的 sizeWithFont 来调整 UILabel 和其他一些控件的大小。我已经更新它们以使用 sizeThatFits 并且它们工作得很好,只是 UIButton 的工作方式与其他按钮不同。 我希望有一个简单的解决方法,例如设置 UIButton 的属性,以使其正常工作?

我的应用只需要支持 ios 8+,而不是旧版本。

更新:根据此处的 cmets How do I resize a UIButton to fit the text without it going wider than the screen? 和接受的答案,似乎我们可能会被 sizeWithFont 或其他低于标准的解决方案卡住...... dang。

【问题讨论】:

不是.sizeToFit 而是.sizeThatFits 两者都是有效的函数。我倾向于 sizeThatFits 是因为它会/应该如何工作,因为你传入了 CGSize,这与我假设使用约束/自动布局规则的 sizeToFit 不同。 好的,但你试过.sizeToFit吗? 好点,我刚刚试了一下。它适用于 UILabel 但对于 UIButton 它使按钮超宽..增加宽度,而不是高度。不过,这给了我一些线索,也许是需要设置一些约束。 当我在 sizeToFit 上搜索 SO 时,我得到的点击量比 sizeThatFits 多得多,所以感谢您为我指明了那个方向。我尝试了一些不同的约束/autoresizingMask,但到目前为止没有运气。根据我一直在阅读的新信息,听起来我现在可能只是被一些“黑客”所困。 【参考方案1】:

我使用 UIButton titleLabel 而不是 UIButton 修复了它。

button.titleLabel?.sizeThatFits(labelFitSize)

代替

button.sizeThatFits(labelFitSize)

好消息是它可以工作,坏消息是如果按钮作为 contentInsets 或图像,你需要自己处理......

【讨论】:

以上是关于可以让 UIButton sizeThatFits 工作吗?的主要内容,如果未能解决你的问题,请参考以下文章

UIButton的探秘

根据 titleLabel 的长度调整 UIButton 的大小

sizeToFit和sizeThatFits

如何让 UILabel 更好地调整大小?

sizeThatFits and sizeToFit

UILabel 的 sizeToFit/sizeThatFits 忽略 numberoflines 属性