1

I have a view controller which has a container view.

I would like to add a UICollectionViewController as a child view controller i.e., add the view of the UICollectionViewController as a subview of the container view and call didMove(toParent:).

I would like the height of the container view to be dynamic so that it depends on the height of the UICollectionViewController's view. I want the height UICollectionView to be equal to its content height.

Can anyone point out how to do this?

This is what I have done till now-

While adding the UICollectionViewController, set translatesAutoresizingMaskIntoConstraints to false, as given in https://stackoverflow.com/a/35431534.

let viewController = CustomCollectionViewController()
viewController.view.translatesAutoresizingMaskIntoConstraints = false
addChild(viewController)
containerView.addSubview(viewController.view)
viewController.didMove(toParent: self)

viewController.view.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
viewController.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
viewController.view.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
viewController.view.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true

I created a custom UICollectionView such that its height depends on its content size as given in https://stackoverflow.com/a/49297382.

class CustomCollectionView: UICollectionView {
    override func reloadData() {
        super.reloadData()
        invalidateIntrinsicContentSize()
    }

    override var intrinsicContentSize: CGSize {
        return collectionViewLayout.collectionViewContentSize
    }
}

Set the above custom UICollectionView as the collectionView of the CustomCollectionViewController using the answer given in https://stackoverflow.com/a/41404946

class CustomCollectionViewController: UICollectionViewController {
    override func loadView() {
        collectionView = CustomCollectionView(frame: .zero, collectionViewLayout: collectionViewLayout)
    }
}

What I have done does not work. Can anyone point out how to do this?

0 Answers0