I have a UIButton
that I add to my view controller\'s view in a storyboard. I add centering constraints to position it and leading space constraints to limit it
/*
In SWIFT : Create an IBDesignable sub class of UIButton and override the intrinsicContentSize as shown below. It will resize appropriately for text and images. Then change your line break property to Word Wrap. Add a "fixedWidth" inspectable property that will adjust the height if you need buttons with fixed widths or when set to false will adjust the width and keep the height fixed.
*/
import UIKit
@IBDesignable
class UIButtonX: UIButton {
//...
@IBInspectable var fixedWidth : Bool = true
override var intrinsicContentSize: CGSize {
let labelSize = titleLabel?.sizeThatFits(CGSize(width: fixedWidth ? frame.width : .greatestFiniteMagnitude, height: fixedWidth ? .greatestFiniteMagnitude : frame.height)) ?? .zero
let wImage = image(for: [])?.size.width ?? 0
let wTitleInset = titleEdgeInsets.left + titleEdgeInsets.right
let wImageInset = imageEdgeInsets.left + imageEdgeInsets.right
let wContentInset = contentEdgeInsets.left + contentEdgeInsets.right
let width : CGFloat = labelSize.width + wImage + wTitleInset + wImageInset + wContentInset
let biggerHeight = max(image(for: [])?.size.height ?? 0, labelSize.height)
let hTitleInset = titleEdgeInsets.top + titleEdgeInsets.bottom
let hImageInset = imageEdgeInsets.top + imageEdgeInsets.bottom
let hContentInset = contentEdgeInsets.top + contentEdgeInsets.bottom
let height : CGFloat = biggerHeight + hTitleInset + hImageInset + hContentInset
let desiredButtonSize = CGSize(width: width, height: height)
return desiredButtonSize
}
//...
}