I am trying to display pre-coded Page/View cells onto their respective cells in my collection view controller.
I've created all the pages without the use of storyboards.
I've created 3 cells but now I am trying to figure out how to put each view into their respective view. I created an array of my 3 classes(pages) but can't figure out how to connect them to separate cells in "cellForItemAt" I tried playing with indexPaths and collectionview.cellForItem(at: ___) but I haven't been able to achieve what I want.
How can I go about connecting the pages in my array to the right cells?
Thanks
let pages = [AboutPageCell, MainPageCell, InfoPageCell]
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
return cell
}
Firstly add this to the ViewController
let cellIdentifier = ["AboutPageCell", "MainPageCell", "InfoPageCell"]
Then in viewDidLoad
register your cells like
tableView.register(AboutPageCell.self, forCellReuseIdentifier: cellIdentifier[0])
tableView.register(MainPageCell.self, forCellReuseIdentifier: cellIdentifier[1])
tableView.register(InfoPageCell.self, forCellReuseIdentifier: cellIdentifier[2])
Your cellForItemAt
will be
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cellToReturn = collectionView.dequeueReusableCell(withIdentifier: cellIdentifier[indexPath.row])
switch indexPath.row {
case 0:
let aboutPageCell = cellToReturn as! AboutPageCell
// Configure you propertie here
cellToReturn = aboutPageCell
case 1:
let mainPageCell = cellToReturn as! MainPageCell
// Configure you propertie here
cellToReturn = mainPageCell
case 2:
let infoCell = cellToReturn as! InfoPageCell
// Configure you propertie here
cellToReturn = infoCell
default:
break
}
return cellToReturn
}