In interface builder, holding Command + = will resize a button to fit its text. I was wondering if this was possible to do programmatically before the
Swift 4.2
Thank god, this solved. After setting a text to the button, you can retrieve intrinsicContentSize which is the natural size from an UIView (the official document is here). For UIButton, you can use it like below.
button.intrinsicContentSize.width
For your information, I adjusted the width to make it look properly.
button.frame = CGRect(fx: xOffset, y: 0.0, width: button.intrinsicContentSize.width + 18, height: 40)
Simulator
UIButtons with intrinsicContentSize
Source: https://riptutorial.com/ios/example/16418/get-uibutton-s-size-strictly-based-on-its-text-and-font