UIStackView's own intrinsicContentSize

simonseyer picture simonseyer · Oct 26, 2015 · Viewed 10.1k times · Source

I'm using the UIStackView with the following configuration:

let contentView = UIStackView()
contentView.distribution = .EqualSpacing
contentView.alignment = .Center
contentView.spacing = horizontalSpacing

Each of the elements has it's own intrinsicContentSize so it should be possible for the UIStackView to provide its own intrinsicContentSize. The documentation states that the spacing is used as a minimum spacing.

Example:

view1: width=10
view2: width=15
spacing = 5
[view1(10)]-5-[view2(15)]

The intrinsicContentSize.width of the stackView should be 30.

Instead I get:

▿ CGSize
 - width : -1.0
 - height : -1.0 { ... }

which tells me that the intrinsicContentSize cannot be provided.

Does anyone of you know if I doing something wrong, if the behaviour is intended or if this is a bug?

Answer

rob mayoff picture rob mayoff · Oct 29, 2015

As of iOS 9.1, UIStackView doesn't implement intrinsicContentSize:

import UIKit
import ObjectiveC

let stackViewMethod = class_getInstanceMethod(UIStackView.self, "intrinsicContentSize")
let viewMethod = class_getInstanceMethod(UIView.self, "intrinsicContentSize")
print(stackViewMethod == viewMethod)

Output:

true

You could make a subclass of UIStackView and implement it yourself if you really need it. You shouldn't need to, though. If UIStackView is allowed (by the constraints on it) to choose its own size, it does so based on its arranged subviews' intrinsic content size (or by other constraints you've set on the sizes of its arranged subviews).