How to add an UICollectionViewLayout programmatically?

Viewed 14887

I'm trying to setup a UICollectionViewLayout programmatically. I'm using a UICollectionView also without using storyboards, as well as settings its constraints.

I've followed Ray Wenderlich tutorial on the subject with some changes to adapt the code to Swift 3 (as AZCoder2 did https://github.com/AZCoder2/Pinterest).

Since all these examples uses storyboards, I've also introduced some changes to create the UICollectionView and its UICollectionViewLayout:

collectionViewLayout = PinterestLayout()
collectionViewLayout.delegate = self
collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: collectionViewLayout)

The result: I can't see anything. If I change the UICollectionViewLayout with the one that Apple provides (UICollectionViewFlowLayout), at least I can see the cells with their content. If I implement some changes and use the storyboard, everything works great but it's not the way I want to accomplish this. The whole view is made programmatically and the collection view is a part of it.

What am I missing? Is it something to do with the way I instantiate the UICollectionViewLayout? Do I have to register something (for example, as I need to register the reusable cell)?

4 Answers

I think this will work.

override init(collectionViewLayout layout: UICollectionViewLayout) {
    super.init(collectionViewLayout: layout)
    collectionView?.collectionViewLayout = YourCollectionViewLayout()
}

I resolved this issue taking these steps:

1 - Changing UICollectionViewController to a UIViewController with a collectionView inside.

2 - On ViewDidLoad I set the delegates and add the view, as usual. Moreover, I instantiate the ViewLayout and use it to instantiate the CollectionView

  var collectionView: UICollectionView?




override func viewDidLoad() {
super.viewDidLoad()

navigationController!.isToolbarHidden = true

let layout = MosaicViewLayout()
layout.delegate = self

collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)

guard let collectionView = collectionView else {
  return
}

view.addSubview(collectionView)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(PhotoCell.self, forCellWithReuseIdentifier: "CharacterCell")
setupCollectionConstraints()

}

3 - On the ViewLayout the protocol stays like this:

protocol MosaicViewLayoutDelegate:class {


func collectionView(_ collectionView: UICollectionView,
                  heightForItemAtIndexPath indexPath: IndexPath) -> CGFloat
}

Don't forget to add the instance inside the class

  weak var delegate: MosaicViewLayoutDelegate?

4 - Add the delegate extension to you ViewController

extension HomeViewImpl: MosaicViewLayoutDelegate {
func collectionView(_ collectionView: UICollectionView, heightForItemAtIndexPath indexPath: IndexPath) -> CGFloat {
let random = arc4random_uniform(4) + 1
return CGFloat(random * 100)
 }
}

enter code here

Related