3

How would I be able to change collection view flow layout to a compositional layout from storyboard. So I have a TabBarController class that contains 3 nav controllers that I init from storyboard looks like this.

//Storyboard is an enum that contains strings IDs that belong to controllers from main storyboard.
private func createNewViewController(storyboardIdentifier: Storyboard.Controller) -> UIViewController {
    let controller = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: storyboardIdentifier.indentifer)

    return controller
}

This is how I add the controllers to the tab bar controller.

viewControllers = [
        SearchCollectionVC(),
        //createNewViewController(storyboardIdentifier: .searchNav),
        createNewViewController(storyboardIdentifier: .todayNav),
        createNewViewController(storyboardIdentifier: .appsNav)

    ]

If I try to add my SearchCollectionVC with the commented line my app crashes. It executes the line fatalError() in the required init from the SearchCollectionVC. This is how I create the layout.

init() {
    super.init(collectionViewLayout: SearchCollectionVC.createCollectionLayout())
}


required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

static func createCollectionLayout() -> UICollectionViewCompositionalLayout {
    let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1))
    let item = NSCollectionLayoutItem(layoutSize: itemSize)

    let grupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(250))
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: grupSize, subitems: [item])

    let section = NSCollectionLayoutSection(group: group)
    section.interGroupSpacing = 20

    let layout = UICollectionViewCompositionalLayout(section: section)

    return layout
}

Now I tried doing this in the SearchCollectionVC viewDidLoad().

collectionView.collectionViewLayout = SearchCollectionVC.createCollectionLayout()

This works with the comment line and without the init. The thing is when I rotate the screen this happens.

enter image description here

This doesn't happen when I add the controller using SearchCollectionVC() and when using the init. Now, I don't know why this is happening. Can someone please let me know how would I be able to init a storyboard controller and change the layout to the compositional layout I created, without having the collection view getting cut in half.Thanks

Luis Ramirez
  • 966
  • 1
  • 8
  • 25

1 Answers1

0

Just found out how to do. Had to create a new collection view like this.

 collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: SearchCollectionVC.createCollectionLayout())
Luis Ramirez
  • 966
  • 1
  • 8
  • 25