Swift中的自定义单元格UICollectionView

时间:2017-07-31 03:37:29

标签: ios swift

我正在尝试为我的collectionView中的每个索引项创建不同的单元格,并且我试图将它们作为各自的单元格向下转换,以便访问它们的变量。 下面的代码输出此错误“无法指定类型'LiveCell.Type'的值以键入'UICollectionViewCell'

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let identifier: String
    let cellName: UICollectionViewCell

    if indexPath.item == 1 {
        identifier = LiveCellId
        cellName = LiveCell
    } else if indexPath.item == 2 {
        identifier = LiveCellId
        cellName = LiveCell
    } else {
        identifier = FeedCellId
        cellName = FeedCell
    }

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! cellName //Trying to downcast cell from the variable called cellName
    cell.homeController = self

    return cell
}

是否有解决方案。提前致谢

2 个答案:

答案 0 :(得分:1)

试试这个: -

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let identifier: String
    let cellName: UICollectionViewCell?

    if indexPath.item == 1 {
        identifier = LiveCellId 
        cellName = LiveCell as? UICollectionViewCell
    } else if indexPath.item == 2 {
        identifier = LiveCellId
        cellName = LiveCell as? UICollectionViewCell
    } else {
        identifier = FeedCellId
        cellName = FeedCell as? UICollectionViewCell
    }

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! cellName //Trying to downcast cell from the variable called cellName
    cell.homeController = self

    return cell
}

答案 1 :(得分:0)

您可以这样做:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let identifier: String


    if indexPath.item == 1 || indexPath.item == 2 {
        identifier = LiveCellId
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! LiveCell 
        cell.homeController = self
        return cell

    } else {

        identifier = FeedCellId
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! FeedCell
        cell.homeController = self 
        return cell
    }


}