2

I am adding a custom UIView to a UIStackView inside a UIScrollView. The custom UIView is created from a XIB without a fixed width. I use autolayout to horizontally constrain the custom view to the UIStackView. All the subviews in the custom view have either a fixed height or an intrinsic height (i.e. labels).

When I add the UIView to the UIStackView, they pile on top of each other, as if they have no height. How do I ensure the correct height of my custom view inside the stack view based on the constraints from interface builder?

Here is how I am adding the custom view to the UIStackView:

CustomView *customView = [CustomView loadFromXib]; // helper to load from xib
customView.translatesAutoresizingMaskIntoConstraints = NO;
[_stackView addArrangedSubview:customView];
[_stackView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[customView]|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:@{@"customView": customView}]];

I suspect the issue involves the intrinsicContentSize of my custom view, but I would think that would be set from the constraints specified for the XIB in interface builder.

jdelman
  • 683
  • 1
  • 6
  • 20
  • 1
    What constraints did you set? It looks like not enough to determine height. `intrinsicContentSize` is for when you view's contents determine a minimum size -- for example the text in a UILabel uses this. – Lou Franco Feb 08 '16 at 21:15
  • So there are fixed vertical spacing constraints between the subviews, plus a few image views with fixed heights, and then a couple labels, which have an intrinsic content size. However, there is one label whose width is set to 75% of the width of the superview with numberOfLines = 0. I suspect that is the culprit. – jdelman Feb 08 '16 at 21:55

1 Answers1

5

I have just come across with this problem in swift, every custom view of mine added to UIStackView seems to be appear in 0 height and all pile on top of each other.

What i did to resolve this problem is that I set the height and width constraint for my custom view before added in to the UIStackView.

let customView = CustomView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 100), customObject: self.customObject)

customView.widthAnchor.constraint(equalToConstant: customView.frame.width).isActive = true
customView.heightAnchor.constraint(equalToConstant: customView.frame.height).isActive = true

contentStackView.insertArrangedSubview(customView, at: 0)
titan
  • 524
  • 1
  • 6
  • 19