Giuseppe Travasoni
Giuseppe Travasoni

Reputation: 137

Wrong frame adding ViewController View as subview

I'm working on a custom scrollView that display different views of different types with pagination.

for view in views {
            view.frame = frame
            frame.origin.x += width
        }
contentViewWidth.constant = width * CGFloat(pages.count)
self.setNeedsUpdateConstraints()

works very well for any kind of custom view subclass.

Now I have to add a ViewController as "page", but doing:

parentViewController?.addChildViewController(containedViewController)
        let width = scrollView.frame.size.width
        let height = scrollView.frame.size.height
        var frame = CGRect(x: 0, y: 0, width: width, height: height)
        containedViewController.view.frame = frame
        pages.append(containedViewController.view)
        contentView.addSubview(containedViewController.view)
        containedViewController.didMove(toParentViewController: parentViewController)

I get the right frame when setting it, bug inspecting the complete scrollview I get a totally random frame size. I'm using the scrollview full screen on a 7plus, su 414 width, but i always get as a result a view with width > 500 px.

What i'm missing?

Upvotes: 1

Views: 738

Answers (1)

Magoo
Magoo

Reputation: 2619

Always better to add a UIView as a container view and set the frame of the viewController.view to that. viewController.view.frame tends to get messy for some reason, especially on rotation / dynamic layout... so try

parentViewController?.addChildViewController(containedViewController)

let width = scrollView.frame.size.width
let height = scrollView.frame.size.height
let frame = CGRect(x: 0, y: 0, width: width, height: height)

let containerView = UIView(frame:frame)

//potentially add flexible width and height   
containedViewController.view.autoresizingMask = [.flexibleWidth,.flexibleHeight]

containedViewController.view.frame = containerView.frame

pages.append(containerView) // assuming this is an array of the views inside the scrollview I'd change that to containerView as well.. bit of a guess though.

containerView.addSubview(containedViewController.view)
contentView.addSubview(containerView)
containedViewController.didMove(toParentViewController: parentViewController)

Upvotes: 1

Related Questions