【问题标题】:Autolayout for UIButton in table view cell not working表格视图单元格中 UIButton 的自动布局不起作用
【发布时间】:2018-07-16 08:11:28
【问题描述】:

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

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

下面是cell的xib设计,

【问题讨论】:

  • 你给 UITableView 单元格的行高是多少?
  • 你使用静态/动态?? ,见相关代码
  • 为 UITableView 单元格添加动态高度
  • ,不管它的内在尺寸如何
  • 是的,我认为按钮大小限制不适合我

标签: ios ios-autolayout autolayout adaptive-layout


【解决方案1】:

您必须实现自己的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
    }
}

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多