ios - 让按钮的宽度和高度增长以适合标题文本

标签 ios swift uibutton autolayout

我有一个带有可变 titleLabel 文本的 UIButton。我想要完成的(使用 AutoLayout)是按钮增长以适合标题,即使标题需要不止一行。所以它必须首先增加宽度,当宽度达到极限时,它必须增加高度以适应标题。如下图场景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 确定按钮的最大宽度是多少?我现在必须手动传递 super View 的框架并“硬编码”按钮约束的常量。

最佳答案

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

关于ios - 让按钮的宽度和高度增长以适合标题文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34750922/

相关文章:

ios - 在 UITableView 中返回 YouTube channel 的视频列表

swift - UILabel 没有出现在 SKScene 上

ios - UIButton.addTarget 无法正常工作。好像是有时间限制的?

ios - UIImage 未在按钮 IBAction 上的 setImage 上更新

ios - 如何在 swift 中添加位置图标?

ios - 在 iAd 的前滚动视频广告中收到错误,但广告播放

ios - 设置 View Controller 不解雇

ios - 如何为 MDCTextField 添加阴影?

ios - 如何在 Swift 中使用 Firebase 属性保存 GeoFire?

ios - 之间的技术区别是什么? &!用快速的语言?