Wei Jay Wei Jay - 3 months ago 44
Swift Question

UICollectionViewCell not shown

I'm building an custom menu in a ViewController, which contains two container view controllers.

Top view is a UICollectionViewController (Flow Layout / Horizontal Scroll Direction)

Bottom view is a UIPageViewController

Everthing works fine. However, when I embedded in a navigation controller, the collectionviewCell dosen't show up as expected, any ideas?

Also, I found that when embedded with navigation controller, the following functions are not called.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { }


Without embedded Navigation Controller

enter image description here
enter image description here

With embedded Navigation Controller

enter image description here
enter image description here

Answer

In you're child view controller containing the collection view, add the code in viewDidLoad and viewDidLayoutSubviews methods as shown below. It should fix your problem.

override func viewDidLoad() {
    super.viewDidLoad()
    self.automaticallyAdjustsScrollViewInsets = false
}

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    self.collectionView.contentInset = UIEdgeInsetsMake(self.topLayoutGuide.length,
                                                        0.0,
                                                        self.bottomLayoutGuide.length,
                                                        0.0)
}

Reason being, by default a UIViewController instance responds being inside a Navigation controller by updating contentInset of UIScrollView subclass (In you're case UICollectionView). So here you are just saying do not automatically update the insets.

Comments