Apple says:

"Container view controllers use this method to return the sizes for their child view controllers. UIKit calls the method as part of the default implementation of the viewWillTransition(to:with:) method for view controllers"

And when i first time launch program:

class ViewController: UIViewController {
                       
override func viewDidLoad() {
    super.viewDidLoad()
    
    let child = ViewControllerChild()
    self.addChildViewController(child)
    self.view.addSubview(child.view)
                    
   
    child.view.translatesAutoresizingMaskIntoConstraints = true
    child.view.autoresizingMask = [.flexibleBottomMargin, .flexibleRightMargin]       
}

override func size(forChildContentContainer container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize {
    return CGSize(width: 100, height: 100)
}

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
}

} I get full parent vc view's size child view controller's view not (100, 100). So what the real point to override it, if i can respond to trait changes by redefining child vc view's frame in (1st load in viewdidload) then in preferredContentSizeDidChange function?

enter image description here

2

There are 2 answers

0
Tarun Tyagi On

From the notes you put in the question :

UIKit calls the method as part of the default implementation of the viewWillTransition(to:with:) method for view controllers

Question: Are you sure that overridden methods are being invoked?

What's missing?

let child = ViewControllerChild()
self.addChild(child)

/// Add this line
child.didMove(toParent: self)

self.view.addSubview(child.view)

Docs : https://developer.apple.com/documentation/uikit/uiviewcontroller/1621405-didmovetoparentviewcontroller

If you are implementing your own container view controller, it must call the didMove(toParent:) method of the child view controller after the transition to the new controller is complete or, if there is no transition, immediately after calling the addChild(_:) method.

1
Honey On

You need to trigger a size change event or actually change the view's size, so that the viewWillTransition method could be called. In your code, the method will never be called because there is no view's size change action. viewWillTransition method notifies the container that the size of its view is about to change.

Please refer this code for your best practice.

EDIT regarding the sizeForChildContentContainer method, here is the detailed use case you can go through with and will help you understand the usage.