首页 文章

让按钮在宽度和高度上增长以适合 Headers 文本

提问于
浏览
0

我有一个带有变量titleLabel文本的UIButton . 我想要完成的(使用AutoLayout)是按钮增长以适应 Headers ,即使 Headers 需要多于一行 . 因此它必须首先在宽度上增长,当宽度达到它的极限时,它必须在高度上增长以适合 Headers . 与下图中的方案C类似:

Autolayout challenge: growing UIButton

首先:我完成了我的目标 . 感谢thisanother帖子我将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弄清楚按钮的最大宽度是多少?我现在必须手动传递superview框架并“硬编码”按钮约束的常量 .

1 回答

  • 3

    您可能使用(多行)UILabel和UIButton以及没有子类来获得该结果 . 将UILabel配置为多行(即0行),并将所有按钮边缘与UILabel的边缘对齐 . UILabel将根据内容调整大小,按钮将跟随 . 然后,您可以使用UILabel作为按钮的文本,或者只是将其放在按钮下面,然后以编程方式复制按钮的文本 .

相关问题