Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can´t add items to UICollectionView inside UIView xib

Objective

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() {
        super.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 {
    ....
}

Problem

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][1]][1] [1]: http://i.stack.imgur.com/zFCeG.png

[![UICollectionView in UIView xib][2][2] [2]: http://i.stack.imgur.com/jKU6z.png

Question

Why am I not able to add items to the UICollectionView inside the UIView xib? How?

like image 814
rilar Avatar asked Jul 09 '16 19:07

rilar


1 Answers

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.

like image 152
Pato Salazar Avatar answered Oct 17 '22 01:10

Pato Salazar