Change UIStackView axis when buttons do not fit?

Earlier I made a UIStackView with 3 UIButtons. By default, the axis is set to Horizontal. If the buttons would be truncated, my goal is to change the axis to Vertical.

Here is what I tried:

private func updateButtons() {
        let buttonsWidth = getButtonWidth(createButton) + 10 +
                           getButtonWidth(updateButton) + 10 +
                           getButtonWidth(deleteButton)
        crudButtons.axis =
        buttonsWidth > crudButtons.bounds.width ?
            .vertical :
            .horizontal
        crudButtons.setNeedsLayout()
    }

    private func getButtonWidth(_ button: UIButton) -> CGFloat {
        return button.titleLabel!.textRect(forBounds: crudButtons.bounds, limitedToNumberOfLines: 1).width
    }

It runs but does not appear to calculate the correct values. How would I properly check if the buttons would be truncated?

Your getButtonWidth() function should probably return button.systemLayoutSizeFitting(size: .zero).width instead (code written in Safari, so may not compile!)

Change UIStackView axis when buttons do not fit?
 
 
Q