Custom UIView from XIB has no height in UIStackVie

2019-08-07 13:50发布

问题:

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.

回答1:

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)