Search code examples
iosios-autolayoutautolayoutadaptive-layout

Autolayout for UIButton in table view cell not working


I have added UIButton to my table view cell with autolayout but UIButton height constraint not working (Already set >=)

enter image description here

Below is my autolayout constraint settings,

enter image description here

Below is the xib design of cell,

enter image description here


Solution

  • You will have to implement your own UIButton subclass that would provide what you want. You can use following TitleAdaptingButton implementation, it overrides intrinsicContentSize to adapt to the text in title label even in vertical axis:

    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
        }
    }
    

    Once you add this class into your project, just set it as a custom class for each of your buttons:

    enter image description here

    But remember, for the buttons to adapt, the cell has to be allowed to define its own size, so you have to use following on your tableView:

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