【发布时间】:2016-01-12 18:10:39
【问题描述】:
我有一个带有可变 titleLabel 文本的 UIButton。我想要完成的(使用自动布局)是按钮会增长以适应标题,即使标题需要多于一行。所以它必须首先增加宽度,当宽度达到极限时,它必须增加高度以适应标题。如下图场景C:
首先:我完成了我的目标。感谢this 和another 发布后,我将 UIButton 子类化,现在该按钮可以按我的意愿工作。这是我的 UIButton 代码:
class JvBstretchableButton: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.titleLabel?.numberOfLines = 0
self.titleLabel?.lineBreakMode = .ByWordWrapping
}
override func intrinsicContentSize() -> CGSize {
return (self.titleLabel?.intrinsicContentSize())!
}
override func layoutSubviews() {
super.layoutSubviews()
/*
Set the preferredMaxLayoutWidth of the titleLabel to the width of the superview minus
two times the known constant value for the leading and trailing button constraints
(which is 10 each). I'm looking for another way to do this. I shouldn't have to hardcode
this right? Autolayout knows the width of the surrounding view and all the relevant constraint
constants. So it should be able to figure out the preferredMaxLayoutWidth itself.
*/
self.titleLabel?.preferredMaxLayoutWidth = superview!.frame.width - 20
super.layoutSubviews()
}
}
但是,我有一种强烈的感觉,我错过了一些东西,并且必须有更简单的方法来做到这一点。这让我想到了我的问题:
A) 真的需要 UIButton 子类,还是有其他更简单的方法?
B) 如果我们不能阻止 UIButton 的子类化:有没有办法让 AutoLayout 计算出按钮的最大宽度是多少?我现在必须手动传递超级视图的框架并“硬编码”按钮约束的常量。
【问题讨论】:
标签: ios swift uibutton autolayout