9
votes

Is there a simple way to get the total content size of a UIStackView?


To give an example:

I programmatically create an array of UIViews...

var numberOfSubViews = 5

let subViews: [UIView] = {
var array: [UIView] = []

for _ in 0..<numberOfSubViews {
    let height: CGFloat = 40
    let width: CGFloat = 100

    let subView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: height))
    subView.widthAnchor.constraint(equalToConstant: width).isActive = true
    subView.heightAnchor.constraint(equalToConstant: height).isActive = true

    array.append(subView)
}

return array
}()

Then I create a simple UIStackView from that array...

var spacing: CGFloat = 4

let stackView = UIStackView(arrangedSubviews: subViews)
stackView.axis = .horizontal
stackView.spacing = spacing
stackView.translatesAutoresizingMaskIntoConstraints = false;

Finally I insert the stackView in an existing view and anchor the top and leading.

view.addSubview(stackView)
stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true

Note that I purposely do not define a height and width constraint or the bottom and trailing constraints. I don't want the subViews or the spacing to be resized based on the stackViews distribution property.

In this simple example, the total content height is 40 (height of the tallest subView).

Total width = width of all subviews + width of all spacing = (100 * 5) + (4 * 4) = 516


When I initialize the subView in this way, the UIStackView's frame and bounds is 0,0,0,0.

1

1 Answers

2
votes

Your example is runs fine on simulator iOS 11.3
use this to get your desired width, after adding you constraints

stackView.layoutIfNeeded() print("width: ", stackView.bounds.width)

add subView.backgroundColor = .red to debug you views