How to load custom cell ( xib) in UICollectionView cell using swift

Here is what you can do,

  1. Change your MyCustomView class to be a subclass of UICollectionViewCell and not UIView.

  2. Remove override init(frame : CGRect),required init?(coder aDecoder: NSCoder),func xibSetup(),func loadViewFromNib() -> UIView from MyCustomView

  3. I seriously could not understand how are you using your setter and getter for mytitleLabelText and myCustomImage. If its of no use get rid of it as well.

  4. Finally you will be left with just IBOutlets in MyCustomView.

  5. For better coding practice change the name from MyCustomView to MyCustomCell (optional)

  6. Go to your xib, select the xib and set its class as MyCustomView.

enter image description here

  1. In the same screen change file owner to yourView controller hosting collectionView

enter image description here

  1. In ViewDidLoad of your viewController register your nib.
self.collectionView.registerNib(UINib(nibName: "your_xib_name", bundle: nil), forCellWithReuseIdentifier: "your_reusable_identifier")
  1. In cellForItemAtIndexPath,
let cell : MyCustomView = collectionView.dequeueReusableCellWithReuseIdentifier("your_reusable_identifier", forIndexPath: indexPath) as! MyCustomView
cell.lblName.text = "bla bla" //access your Cell's IBOutlets
return cell
  1. Finally in order to control the size of cell either override the delegate of collectionView or simply go to your collectionView select the collectionCell in it and drag it to match your dimension :) Thats it :)

Happy coding. Search tutorials for better understanding. I can't explain all delegates as I'll end up writing a blog here.

Happy coding


For Swift 4.0

in viewDidLoad:

//custom collectionViewCell
mainCollectionView.register(UINib(nibName: "your_customcell_name", bundle: nil), forCellWithReuseIdentifier: "your_customcell_identifier")

in cellForItemAt indexPath:

let cell : <your_customcell_name> = mainCollectionView.dequeueReusableCell(withReuseIdentifier: "your_customcell_identifier", for: indexPath) as! <your_customcell_name>

And dont forget to set identifier for your custom cell in xib section.

Tags:

Ios

Ipad

Swift

Xib