Determine UIStackView contentsize
Asked Answered
D

1

10

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.

Develop answered 19/3, 2017 at 4:56 Comment(0)
H
2

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

Hydrocellulose answered 18/6, 2018 at 7:43 Comment(2)
Yes, layoutIfNeeded() is a "swiss knife" for many frame-related issues. :)Rebbecarebbecca
Correct bro, you saved my day!Provocation

© 2022 - 2024 — McMap. All rights reserved.