Container view with dynamic height inside UIScrollView with auto layout

前端 未结 3 1484
灰色年华
灰色年华 2021-02-02 15:03

I have a UIScrollView, nested inside of which in one content view and it has two child views nested, a regular UIView with a known height, and a container view with dynamic heig

相关标签:
3条回答
  • 2021-02-02 15:39

    In your case if you want to get rid of the IB warnings about the Container height should be zero. you can put a height constraint with whatever constant value suitable for you and check it as a placeholder (it will be removed at build time.)

    0 讨论(0)
  • 2021-02-02 15:43

    There were two things I found that helped me work around this same issue.

    Issue 1: Height of Container

    I want the container view to resize itself, but IB wants an explicit height on the container view. Since IB doesn't know anything about the content of the view, it has no way of knowing the content of the container view can size itself. The simplest way to do that is to set a Placeholder Intrinsic Content Size from the Size Inspector for the container view:

    Size Inspector

    This effectively results in making IB happy without applying any height constraint. Another option is to add a "Remove at build time" height constraint on the container.

    Issue 2: Height of Child View Controller View

    The root view of the child view controller defaults to using an AutoresizingMask, as is standard for the topmost view in any UIViewController. My solution to this is to disable use of AutoresizingMask in prepareForSegue, when the child view controller is added. Try the following in the parent view controller:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        super.prepare(for: segue, sender: sender)
    
        if let childViewController = segue.destination as? ChildViewControllerClass {
            childViewController.view.translatesAutoresizingMaskIntoConstraints = false
        }
    }
    

    Making the change in the parent view ensures that if the child view is re-used elsewhere inside a UINavigationController, the view will be sized correctly.

    Before I made that change, I kept getting AutoLayout errors conflicting with constraints called UIView-Encapsulated-Layout-Height, which I believe is the name for constraints derived from AutoresizingMask based layout on the root UIViewController view.

    0 讨论(0)
  • 2021-02-02 15:45

    You must provide enough constraints information in the UIScrollView so that it can calculate its contentSize. For you case, you must provide height constraint for you container view. You can IBOutlet the height constraint and update its value accordingly.

    0 讨论(0)
提交回复
热议问题