Instructions to combine UICollectionViews with UITableViewCell Xib

Tram Ho

I had some difficulty combining UICollectionView with UITableViewCell, so now I read many different sources and now I will summarize and form a clearer guide.

** Note: This article is not for beginners, by default you already know about tableView and creating cell options with xib files.

And it will not do anything to make your interface look good, just run the code, and display it as required **.

Start by creating a project with a tableView, which is connected via the storyboard, in addition to creating an xib file and the UITableViewCell class to associate with the UICollectionView.

1. Add UICollectionView to the Xib TableViewCell file

  1. Drag and drop a collection view
  2. More constraints
  3. Find out why you can’t add CollectionViewCells to the collection view you’ve just dropped above

And actually you need a separate file to contain any collection of cell views you want to display. (When your UICollectionView is in an Xib file)

2. Add 1 file and 1 Xib UICollectionViewCell to your Project

You can do this whatever you want to display with Xib CollectionViewCell, for the purpose of this tutorial, I just changed their background color.

Make sure you give your cell a resuableIdentifier

3. Structure your TableViewCell class with UICollectionView Data Source and Delegate protocols

Step 1: Return to the Xib tableViewCell file

Step 2: Go to the Outline Document

Step 3: Drag and drop from your collectionView to ‘File Owner’ and select dataSource and then the delegate. (Can hold Cmd key to select simultaneously)

Step 4: Connect your collectionView to the TableViewCell class through creating an IBOutlet, drag and drop

Step 5: Configure your tableViewCell class in accordance with UICollectionViewDelegate and UICollectionViewDataSource

  1. Add UICollectionViewDelegate and UICollectionViewDataSource protocols in the class extension
  2. Connect collectionView’s data source and delegate = self in awakeFromXib
  3. Add the numberOfItemsInSection function
  4. Add the cellForItemAt function
  5. Create a cell with your reuseIdentifier and cast the cell type you customized

At this point, it will crash. We need to register the nib file or class for identifiers or connect a cell attribute in the storyboard.

4. Register your Xib

In the awake section of your tableViewCell, add this line:

Compile and execute, it will work. Next is the code addition for tableViewCell

The problem may be encountered

  • The wrong identifier and the wrong connection?
  • Did drag and drop collectionView into File’s Owner in the Xib file yet?

Hope this post will help you.

Share the news now

Source : Viblo