【问题标题】:Displaying views onto specific Collection View Cells?在特定的集合视图单元格上显示视图?
【发布时间】:2019-04-13 02:45:32
【问题描述】:

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

我在没有使用情节提要的情况下创建了所有页面。

我已经创建了 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
}

【问题讨论】:

  • 您在哪里创建了单元格的视图?在 .xib 或情节提要中?
  • 抱歉,我忘了说,我都是在没有情节提要的情况下以编程方式创建的。

标签: ios swift xcode collectionview


【解决方案1】:

首先将其添加到 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
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多