2017-07-31 96 views
0

我想为我的collectionView中的每个索引项目创建不同的单元格,并且我试图将它们作为它们各自的单元格向下翻转以访问它们的变量。下面 该代码输出这个错误“无法分配类型的值‘LiveCell.Type’为类型‘UICollectionViewCell’Swift中的自定义单元格UICollectionView

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 
} 

是否有一个解决方案。在此先感谢

回答

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 
    } 


} 
+0

伟大的作品。谢谢 –

0

试试这个: -

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 
} 
+0

看起来像它会但它给了我“,从‘FeedCell.Type’无关型演员'UICollectionViewCell'总是失败“ –

相关问题