簡體   English   中英

表格視圖單元格中 UIButton 的自動布局不起作用

[英]Autolayout for UIButton in table view cell not working

我已使用自動布局將 UIButton 添加到我的表格視圖單元格中,但 UIButton 高度約束不起作用(已設置 >=)

在此處輸入圖片說明

下面是我的自動布局約束設置,

在此處輸入圖片說明

下面是單元的xib設計,

在此處輸入圖片說明

你必須實現你自己的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM