问题描述
我正在准备一个与屏幕截图中显示的示例类似的自定义视图.我在运行时添加所有用户界面组件(标签、文本字段、单选按钮……).要定位我使用的元素 自动布局 约束.到目前为止,这部分工作正常.
I am preparing a custom view which looks similar to the example shown in the screenshot. I add all user interface components (labels, text fields, radio buttons, ..) at runtime. To position the elements I use Autolayout constraints. This part works fine so far.
元素的数量因上下文而异.我想知道如何使用 Autolayout 约束来动态调整父视图的大小(很可能是视图的高度).因此,视图约束应考虑为当前附加的子视图定义的高度和边距.
The number of elements varies from context to context. I wonder how I could use Autolayout constraints to dynamically resize the parent view (most likely the height of the view). The view constraints therefore should consider the height and margins defined for the currently attached subviews.
推荐答案
我已经通过以下设置完成了这个:
I've done this with the following setup:
- 容器视图没有高度限制
- 顶部子视图与容器视图顶部有间距约束
- 包含的视图之间都有间距限制
- 底部视图对容器视图底部有间距限制
自动布局系统通过调整容器大小以适应其内容来满足这些约束.
The auto layout system satisfies these constraints by resizing the container to fit its contents.
当然,您需要在更改内容时动态设置约束.
Of course, you need to dynamically set the constraints as you alter the contents.
这篇关于如何根据使用 Autolayout 布局的子视图的大小调整父视图的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!