swiftuikituibuttonstoryboard

How to make UIButton width same as text width on its label?


I am trying to set my button width equal to text length. But width of my button is not changing. My button is inside a vertical stack view. Stack view has two views. Text is the button title label. My stack is placed on super view which has same leading and trailing as superview and placed vertically and horizontally centred.

@IBOutlet private weak var myButton: UIButton! {
    didSet {
        myButton.style = .textOnly
        myButton.contentHorizontalAlignment = .right
        myButton.setAttributedTitle(textlabel, for: .normal)
        myButton.frame.size.width = CGFloat(textlabel.length) + 16
    }
}

Am I missing here something?


Solution

  • All views (buttons, labels, image views, etc) added to a UIStackView as arranged subviews automatically have .translatesAutoresizingMaskIntoConstraints set to false.

    So, this line:

    myButton.frame.size.width = CGFloat(textlabel.length) + 16
    

    does nothing.

    The default .alignment for a stack view is .fill, which mean the width of an arranged subview will be equal to the width of the stack view.

    If you don't want that, you need to set:

    stackView.alignment = .center
    

    Of course, that means you need to set width constraints on any arranged subviews that are not using their intrinsic content size.