0

I have created the most simple of Apps, Xcode 9.2, New Project/Single View App/Next/Next etc. and replaced the ViewController with a CollectionViewController.

This is the entire code of the CollectionViewController, and note self.collectionView!.backgroundColor = UIColor.yellow to set the background color to yellow.

This works fine. When I rotate the iPhone in the simulator, it does not seem to invalidate the ViewController, as seen by yellow not extending the entire width of the phone when the phone is horizontal.

rotated iPhone in simulator

Here is my code.

import UIKit

class CollectionViewController : UICollectionViewController, UICollectionViewDelegateFlowLayout {

override func viewDidLoad() {
    super.viewDidLoad()
    self.collectionView!.backgroundColor = UIColor.yellow
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    print("test-1")
    let x1 = self.collectionViewLayout;
    //x1.invalidateLayout()   //uncomment this line
    print("test-2")
   }
}

I thought I understood this, and I searched the Apple forums and StackOverflow too (here is a really relevant prior posting), and it appears I need to invalidate the collection view manually in code.

If I remove the comment from line //x1.invalidateLayout() xCode prints out in the output window "test-1" and "test-2" in an infinite loop.

A pointer to push me into the right direction here would be most welcome. Clearly when the iPhone is rotated in the simulator, horizontally it should cover the entire screen in yellow too.

Thank you.

Steve
  • 77
  • 6
  • First as it is the background of the entire collection view that you have made yellow and not just any contained cells, etc then it shouldn't be layout related. Secondly if you uncomment your line the invalidation is forcing the viewDidLaoutSubviews to be called again and thus an infinite loop. It's likely to be related to how you replaced the view controller with the collection view controller when you set it up in the storyboard. – Upholder Of Truth Dec 30 '17 at 15:25
  • Problem solved, sort of. If I check the box "Is Initial View Controller" for the replacement CollectionViewController it works as expected. Why, I do not know – Steve Dec 30 '17 at 16:55
  • That indicates that it is the first controller to load and installed as the root for your application. Good to know it's working. – Upholder Of Truth Dec 30 '17 at 17:08

0 Answers0