问题
This is what I'm trying to do...
I have one view controller that needs to dynamically display different subviews based on the presence of some data.
Here is a simple mockup. Each colored block represents a unique subview.
Sometimes the green block needs to be at the top, sometimes the green block won't display at all, sometimes the light blue block will be something different, etc.
Each subview has interactive elements, so I've been creating and adding them like so:
- Defining a new view controller
- Defining its view
- Calling
addChildViewController
anddidMoveToParentViewController
- Calling
addSubview
onmyNewViewController.view
- Using SnapKit to make auto layout constraints to position the view
I want to transition to UIStackView
because it seems a good support system for this view because all I need to do is stack its subviews. I'm seeing many conflicting constraint errors and unexpected view frames when trying to add subviews with their own inner auto layout constraints.
Question
Am I setting myself up for failure here by embedding the views of 4-6 view controllers in the view of one view controller?
Also, how do I give the added views properties like minimum heights or content sizes without seeing many breaking constraints with UIStackView
? (So they can stack, but one of them is say, 400 tall, and the other is 200 tall)
回答1:
Answer
You can absolutely do this using UIContainerViews
combined with UIStackViews
and UIScrollViews
, it's a complicated setup so here's a starter project to get you started:
https://github.com/Rnorback/ScrollingStackView
Here's what that project looks like:
You want the containers to have different sizes. In order to do that, simply add height constraints to the containers with Autolayout. If you want to change the height of the scrolling. Then you'll need to change the height constraint of the UIStackView
.
Brief Explanation
When creating this setup, you have to make sure the UIStackView
distribution
setting stays in fill. That way you can set height constraints on UIContainerViews.
When setting up anything in a UIScrollView
you have to make sure that the object is pinned to the edges of the scroll view and has a defined width and height, otherwise the scrollview will throw a constriant error. I think of it like the scrollview tries to press in on all sides of your content view and if any side gives, the scrollview won't be able to present it properly.
Hope this helps.
来源:https://stackoverflow.com/questions/32912132/how-do-i-prepare-a-uiviewcontrollers-view-for-being-added-to-a-uistackview