ios - TableView 单元格中 UIButton 的自动布局不起作用

标签 ios ios-autolayout autolayout adaptive-layout

我已使用自动布局将 UIButton 添加到我的表格 View 单元格,但 UIButton 高度约束不起作用(已设置 >=)

enter image description here

下面是我的自动布局约束设置,

enter image description here

下面是cell的xib设计,

enter image description here

最佳答案

您必须实现您自己的 UIButton 子类来提供您想要的内容。您可以使用以下 TitleAdaptingButton 实现,它会覆盖 intrinsicContentSize 以适应标题标签中的文本,即使在垂直轴上也是如此:

class TitleAdaptingButton: UIButton {

    override var bounds: CGRect {
        didSet {
            if !oldValue.equalTo(bounds) {
                invalidateIntrinsicContentSize()
            }
        }
    }

    override var intrinsicContentSize: CGSize {
        get {
            let labelSize = titleLabel!.sizeThatFits(CGSize(width: frame.width - (titleEdgeInsets.left + titleEdgeInsets.right), height: .greatestFiniteMagnitude))
            let desiredButtonSize = CGSize(width: labelSize.width + contentEdgeInsets.left + contentEdgeInsets.right, height: labelSize.height + contentEdgeInsets.top + contentEdgeInsets.bottom)
            return desiredButtonSize
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.titleLabel?.numberOfLines = 0
        // if you want the text centered
        //        self.titleLabel?.textAlignment = .center
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.titleLabel?.numberOfLines = 0
        // if you want the text centered
        //        self.titleLabel?.textAlignment = .center
    }
}

将此类添加到项目中后,只需将其设置为每个按钮的自定义类即可:

enter image description here

但请记住,为了适应按钮,必须允许单元格定义自己的大小,因此您必须在 tableView 上使用以下内容:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44 // or your better estimation

关于ios - TableView 单元格中 UIButton 的自动布局不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48640055/

相关文章:

ios - 如何将 `Observable` 转换为 `ControlEvent`

ios - 如何在 Xcode 5 及更高版本中删除派生数据和清理项目?

ios - 以编程方式相对于安全区域的底部定位 View

ios - 带有 UITableViewCellAccessoryDisclosureIndicator 的 UITableViewCell 删除右边距

ios - 如何统计SOAP的元素名称?

ios - AppStore verifyReceipt 在沙盒中返回 21007

swift - 使用layoutAnchor填充 super View

swift - 如何将 UICollectionViewCell 的背景图像获取到旋转时的单元格的spectFit?

ios - UICollectionCell 位置问题

objective-c - Cocoa 自动布局和调整 subview 的大小