I have added UIButton to my table view cell with autolayout but UIButton height constraint not working (Already set >=)
Below is my autolayout constraint settings,
Below is the xib design of cell,
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:
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