Custom UIView from XIB has no height in UIStackView

为君一笑 提交于 2019-12-24 15:24: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)


来源:https://stackoverflow.com/questions/35276241/custom-uiview-from-xib-has-no-height-in-uistackview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!