I am trying to implement a UICollectionViewController programatically (NOT using the storyboard, although my project does use a storyboard for other things). I am able to connect my data source and display the number of cells that correspond to the number of hits from my index, but the cells are blank and generic; my custom cell doesn't appear as expected.
import UIKit
import InstantSearch
private let reuseIdentifier = "CollectionGridCell"
class ResultsCollectionViewController: UICollectionViewController, HitsController {
var hitsSource: HitsInteractor<Test>?
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(CollectionGridCell.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionView.backgroundColor = .clear
// Do any additional setup after loading the view.
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return hitsSource?.numberOfHits() ?? 0 }
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionGridCell
// Configure the cell
let hit = hitsSource?.hit(atIndex: indexPath.row)
cell.backgroundColor = UIColor.red
return cell
}
}
This UICollectionTableViewController is part of a StackView. From the parent VC, it's initialized like this:
let hitsCollectionController = ResultsCollectionViewController(collectionViewLayout: UICollectionViewFlowLayout())
stackView.addArrangedSubview(hitsCollectionController.collectionView)
This is what I see. Note that the number of squares accurately reflects how many items I have in my data source.
Here is my xib file, if that helps any.
What I expected to happen is that the cells should have a label with "Test" inside them that I can set based on the hit. Instead, they're just blank and seem like the default cells. My cell isn't registering/displaying properly. I have a feeling it has something to do with the layout settings, but I'm really not sure. I have a corresponding table view that works just fine.
You've created the cell in a nib file so you need to register it with the nib initializer by providing the nib file name.
collectionView.register(UINib(nibName: <#T##String#>, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier) // provide the nib file name in the placeholder