如何在 swift 3 中的集合视图控制器中使用自定义单元格

how to use custom cell in collection view controller in swift 3

我正在使用 swift 3 - 我知道如何使用自定义 Cell 在集合视图中显示一些图像 - 问题是我无法在 Collection View Controller

这里是集合视图控制器代码 private let reuseIdentifier = "uploadCell"

class 上传文件: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
}

这里是 Collection view Cell Code

   import UIKit

  class UICollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var cellImages: UIImageView!
   }

记住我使用 "uploadCell" 作为标识符

使用 CollectionView 自定义单元格

第 1 步:创建 CollectionViewCell

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

第 2 步:在 StoryBoard 中设置 CollectionViewCellclass

第 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
}

UICollectionView 的实现很有趣。您可以从这些 link :

中获得非常简单的源代码和视频教程

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
}