rilar rilar - 4 months ago 75
Swift Question

Can´t add items to UICollectionView inside UIView xib


I wanna place my (BusinessViewTableHeader: UIView) as tableView header:

tableView.tableHeaderView = BusinessViewTableHeader.instanceFromNib() as! BusinessViewTableHeader

Inside BusinessViewTableHeader there is a UICollectionView which are supposed to display images when swiped, much like the Tinder app.

This is my UIView subclass:

class BusinessViewTableHeader: UIView {

@IBOutlet var collectionView: UICollectionView!

override func awakeFromNib() {
self.collectionView.delegate = self
self.collectionView.registerNib(UINib(nibName: "BusinessImageCollectionCell", bundle: nil), forCellWithReuseIdentifier: "BusinessImageCollectionCell")

class func instanceFromNib() -> UIView {
return UINib(nibName: "BusinessViewTableHeader", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView


extension BusinessViewTableHeader: UICollectionViewDelegate, UICollectionViewDataSource {


I have a custom UIView xib containing a UICollectionView. The problem is that I canĀ“t add any cells (items) to the UICollectionView. I can add items to my other UICollectionView which are placed inside a UIViewController. The first image is showing the properties for the UICollectionView inside a UIViewController, the second image is showing the UICollectionView inside a UIView xib.

UICollectionView in UIViewController
[UICollectionView in UIView xib2


Why are I not able to add items to the UICollectionView inside the UIView xib? Is there a way of doing this?


Stupid misstake, I forgot:

self.collectionView.dataSource = self


You can't have UICollectionViewCell when the UICollectionView is on a Nib. What you need to do is to create the UICollectionViewCell as another nib and get it registered in the class that you are using for your CollectionView.

Create a new nib, drag a UICollectionViewCell inside it, and do something like this in the class that works with your UICollectionView

override func awakeFromNib() {

    let nibName = UINib(nibName: "ClassCollectionCell", bundle:nil)

    collectionView.registerNib(nibName, forCellWithReuseIdentifier: "collectionCell")

Remember you can add a custom class to the UICollectionViewCell so you can pass dynamic data to it.