来自 XIB 的自定义 UIView 在 UIStackView 中没有高度 [英] Custom UIView from XIB has no height in UIStackView

查看:64
本文介绍了来自 XIB 的自定义 UIView 在 UIStackView 中没有高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向 UIScrollView 内的 UIStackView 添加自定义 UIView.自定义 UIView 是从没有固定宽度的 XIB 创建的.我使用自动布局将自定义视图水平约束到 UIStackView.自定义视图中的所有子视图都具有固定高度或固有高度(即标签).

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).

当我将 UIView 添加到 UIStackView 时,它们彼此堆叠在一起,就好像它们没有高度一样.如何根据界面构建器的约束确保堆栈视图内自定义视图的正确高度?

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?

这是我将自定义视图添加到 UIStackView 的方法:

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}]];

我怀疑该问题涉及我的自定义视图的 intrinsicContentSize,但我认为这将根据为界面构建器中的 XIB 指定的约束进行设置.

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.

推荐答案

我刚刚在 swift 中遇到了这个问题,我添加到 UIStackView 的每个自定义视图似乎都出现在 0 高度并且全部堆在每个视图的顶部其他.

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.

我为解决这个问题所做的是在添加到 UIStackView 之前为我的自定义视图设置了高度和宽度约束.

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)

这篇关于来自 XIB 的自定义 UIView 在 UIStackView 中没有高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆