简体   繁体   English

来自XIB的自定义UIView在UIStackView中没有高度

[英]Custom UIView from XIB has no height in UIStackView

I am adding a custom UIView to a UIStackView inside a UIScrollView. 我将自定义UIView添加到UIScrollView中的UIStackView。 The custom UIView is created from a XIB without a fixed width. 自定义UIView是从没有固定宽度的XIB创建的。 I use autolayout to horizontally constrain the custom view to the UIStackView. 我使用autolayout将自定义视图水平约束到UIStackView。 All the subviews in the custom view have either a fixed height or an intrinsic height (ie labels). 自定义视图中的所有子视图都具有固定高度或固有高度(即标签)。

When I add the UIView to the UIStackView, they pile on top of each other, as if they have no height. 当我将UIView添加到UIStackView时,它们堆叠在一起,好像它们没有高度。 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: 以下是我如何将自定义视图添加到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. 我怀疑该问题涉及我的自定义视图的intrinsicContentSize ,但我认为这将根据在界面构建器中为XIB指定的约束进行设置。

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. 我刚刚在swift中遇到过这个问题,我添加到UIStackView的每个自定义视图似乎都出现在0高度并且所有堆叠在彼此之上。

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. 我解决这个问题的方法是在添加到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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM