显示特定 Collection View Cells 的视图?

Displaying views onto specific Collection View Cells?

我正在尝试将预编码的 Page/View 单元格显示到我的集合视图控制器中它们各自的单元格上。

我在没有使用故事板的情况下创建了所有页面。

我已经创建了 3 个单元格,但现在我想弄清楚如何将每个视图放入各自的视图中。我创建了一个包含 3 类(页面)的数组,但无法弄清楚如何将它们连接到 "cellForItemAt" 中的单独单元格 我尝试使用 indexPaths 和 collectionview.cellForItem(at: ___) 但我一直无法实现我想要的。

如何将数组中的页面连接到正确的单元格?

谢谢

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
}

首先将此添加到 ViewController

let cellIdentifier = ["AboutPageCell", "MainPageCell", "InfoPageCell"]

然后在viewDidLoad注册你的单元格

tableView.register(AboutPageCell.self, forCellReuseIdentifier: cellIdentifier[0])
tableView.register(MainPageCell.self, forCellReuseIdentifier: cellIdentifier[1])
tableView.register(InfoPageCell.self, forCellReuseIdentifier: cellIdentifier[2])

您的 cellForItemAt 将是

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
    }