【问题标题】:how to use custom cell in collection view controller in swift 3如何在 swift 3 的集合视图控制器中使用自定义单元格
【发布时间】:2017-10-30 15:27:45
【问题描述】:

我正在使用 swift 3 - 我知道如何使用自定义单元格在集合视图中显示一些图像 - 问题是我无法在 集合视图控制器 中使用自定义单元格

这里是集合视图控制器代码 私有让重用标识符 = "uploadCell"

上传文件类:UICollectionViewController {

var images = ["1.jpg" , "2.jpg" , "3.jpg" , "4.jpg"  ]

 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
    //myCollectionView.sizeToFit()
    //cell.sizeToFit()


    cell.cellImages.image = UIImage(named: images[indexPath.row])



    return cell
}

这里是集合视图单元格代码

   import UIKit

  class UICollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var cellImages: UIImageView!
   }

记得我使用“uploadCell”作为标识符

【问题讨论】:

  • 单元格在情节提要中还是在自己的xib中?
  • 没有单元格在故事板中
  • @SaeedRahmatolahi 为什么您的自定义类以 UICollectionViewCell 命名?那么你如何区分你的自定义类和 iOS UICollectionView?不要使用 Apple 预定义的类
  • 我使用了很多名字但是在 cell.image 行中我得到了错误

标签: ios image swift3 uicollectionview uicollectionviewcell


【解决方案1】:

对于使用 CollectionView 自定义单元格

第 1 步:创建 CollectionViewCell 的子类

class ImageCell: UICollectionViewCell {
    @IBOutlet weak var imgView: UIImageView!
}

第 2 步:在 StoryBoard 中设置 CollectionViewCell 类

第 3 步:重用CollectionView 单元格

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell

    cell.imgView.image = self.arrMedia[indexPath.row] as? UIImage
    return cell
}

【讨论】:

    【解决方案2】:

    UICollectionView 的实现非常有趣。您可以从这些链接中获得非常简单的源代码和视频教程:

    https://github.com/Ady901/Demo02CollectionView.git

    https://www.youtube.com/watch?v=5SrgvZF67Yw

    class DummyCollectionCell: UICollectionViewCell {
    
        @IBOutlet weak var userImageView: UIImageView!
        @IBOutlet weak var titleLabel: UILabel!
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DummyCollectionCell", for: indexPath) as! DummyCollectionCell
                    cell.titleLabel.text = nameArr[indexPath.row]
                    cell.userImageView.backgroundColor = .blue
                    return cell
    }
    

    【讨论】: