Alan Alan - 1 year ago 172
Swift Question

how to create uicollectionview with swift programatically (without storyboard)

i am trying to create a uicollectionview with swift programmatically, without any storyboard. and i need it to be multiple uicollectionview.
this is my code

class jobtypeViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource{
var collectionview1 = UICollectionView()
var collectionview2 = UICollectionView()

override func viewDidLoad() {

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 100, height: 100)

collectionview1 = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
self.collectionview1.delegate = self
self.collectionview1.dataSource = self
collectionview1.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")

collectionview2 = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
self.collectionview2.delegate = self
self.collectionview2.dataSource = self
collectionview2.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.collectionview1 {
return 5
return 4

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if collectionView == self.collectionview1 {
let cellA = collectionview1.dequeueReusableCellWithReuseIdentifier("Cell",forIndexPath: indexPath) as UICollectionViewCell
return cellA

else {
let cellB = collectionview2.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell
return cellB


everything seem fine i have the layout,delegate,and datasource, but when i run it i got this message error Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'UICollectionView must be initialized with a non-nil layout parameter'. did i miss something??

Answer Source

Your initializers look correct, however, your member variables are initialized with an empty initializer which will be evaluated before viewDidLoad is triggered

 var collectionview1 = UICollectionView()

You can change it to be implicitly unwrapped since you're initializing these values right away in your viewDidLoad

var collectionview1: UICollectionView!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download